有人可以告诉我知道联合是全局队列结构的成员的情况下,如何使用写函数保持分配给联合成员的值?
基本上,我所做的是定义一个带有队列名称,长度和互斥量的数据队列缓冲区结构(用于读写功能之间的同步)。缓冲区数据是不同系统的存储结构。联合用于封装所有不同的结构。为每个系统(eps_q,com_q..etc)创建了队列结构的不同实例。
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
typedef union qbuf{
eps_hk eps_buf[EPS_HK_SIZE];
odb_hk odb_buf[ODB_HK_SIZE];
com_hk com_buf[COM_HK_SIZE];
cam_hk cam_buf[CAM_HK_SIZE];
adcs_hk adcs_buf[ADCS_HK_SIZE];
}qbuf_t;
typedef struct {
qbuf_t qbuf;
int qwindex;
int qlength;
int qfull;
char *qname;
pthread_mutex_t *qmut;
pthread_cond_t *qFull;
}queue;
queue *odb_q;
queue *eps_q;
queue *com_q;
queue *cam_q;
queue *adcs_q;
/*************************************************/
/**** read and write functions in eps.c *****/
int eps_queueAdd (queue *q, eps_hk hk)
{
q->qbuf.eps_buf[q->qwindex] = hk;
printf(".... After queue add..... vbatt %u\n", q->qbuf.eps_buf[q->qwindex].vbatt);
q->qwindex++;
if (q->qwindex == q->qlength) {
q->qwindex = 0;
q->qfull=1;
}
return (q->qfull);
}
eps_hk eps_queueRead(queue *q) //read hk from local eps hk table, for hk handlers
{
eps_hk hk;
sleep (10);
hk = q->qbuf.eps_buf[q->qwindex];
printf(".... INSIDE queue read .....vbatt %u \n", q->qbuf.eps_buf[q->qwindex].vbatt);
return (hk);
}
写函数(queueADD)很好用,这里的问题是当我尝试读取以前使用(queueADD)(比如10)编写的值时,我似乎找不到它(我得到0 )。
谢谢您抽出宝贵的时间阅读我的帖子=)
===编辑============================================ =====================
在队列结构中使用联合的目的是为不同的数据类型定义通用队列。当然,我曾考虑过使用void *指针,但这在内存分配和指针解引用方面太麻烦了。你觉得呢?
答案 0 :(得分:1)
队列中需要一个枚举,告诉您选择了哪个工会成员。示例:
typedef enum
{
qbuf_select_eps = 0;
qbuf_select_odb;
qbuf_select_com;
qbuf_select_cam;
qbuf_select_adcs;
}qbuf_select_t;
typedef struct {
qbuf_t qbuf;
qbuf_select_t qbuf_select;
int qwindex;
int qlength;
int qfull;
char *qname;
pthread_mutex_t *qmut;
pthread_cond_t *qFull;
}queue;
在功能上,您可以使用像这样的开关。
queue *q;
...
switch (q->qbuf_select)
{
case qbuf_select_eps:
//Operations on q->qbuf.eps_buf
break;
case qbuf_select_com:
//Operations on q->qbuf.com_buf
break;
...
}
我使用了此解决方案,并且工作正常。
答案 1 :(得分:0)
好吧,在您的写入功能中,您可以更新/增加索引(又名qwindex
),而在读取功能中,您可以使用相同索引来进行读取。因此,读取功能将在您最后写入的元素之后(之后)返回元素(即尚未写入的元素)。
我希望read函数可以
1)为要阅读的元素建立索引
或
2)使用qwindex - 1
作为索引(然后递减索引以获得类似堆栈的行为)。
或者也许您需要一个索引进行写操作,并需要另一个索引进行读操作,以便返回最早的元素(FIFO行为)。