我在C中实现FIFO。一个线程在FIFO中写入,另一个线程从中读取。
#define BUFFER_LENGTH 1000
struct Frame
{
char data[1024];
unsigned int data_len;
struct Frame* frame;
};
struct Frame * get_from_fifo ()
{
if (!fifo_length)
{
first = last = NULL;
return NULL;
}
struct Frame* frame = first;
first = first->frame;
fifo_length--;
return frame;
}
int add_to_fifo (const char* data, unsigned int frame_size)
{
if (fifo_length >= BUFFER_LENGTH)
{
ast_log(LOG_ERROR, "Buffer fulln");
return SURESH_ERROR;
}
struct Frame* frame = malloc(sizeof (struct Frame));
frame->data_len = frame_size;
memcpy(frame->data, data, frame_size);
if (last)
{
last->frame = frame;
last = frame;
}
if (!first)
{
first = last = frame;
}
fifo_length++;
return SURESH_SUCCESS;
}
如何防止函数*add_to_fio*和*get_from_fifo*被不同的线程同时调用。即*get_from_fifo*应该只在另一个线程没有执行*add_to_。
在实现FIFO堆栈时,只有真正并发的操作是更改堆栈大小(fifo_length
)
您将向堆栈的尾部添加条目,并从堆栈的头部删除条目,这样这两个操作就不会相互干扰。因此,您唯一需要担心的部分是更改堆栈大小(fifo_length
),我会将其放入由互斥或标志同步的单独函数中(如上面的"Joey"所述),并从add_to_fifo()
和get_from_fifo()
函数中调用它。
您需要使用互斥(mutual exclusion)变量。pthread库提供了您所需的一切。这里是一个开始查看可用功能的好地方:
http://pubs.opengroup.org/onlinepubs/009695399/basedefs/pthread.h.html
您需要初始化一个互斥变量,每个线程都可以访问该变量:http://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_mutex_init.html
然后,您的线程需要在需要访问共享内存时将其锁定,然后在使用共享内存时解锁:http://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_mutex_lock.html
下面是一个简单的例子:http://publib.boulder.ibm.com/infocenter/iseries/v5r3/index.jsp?topic=%2Frzahw%2Frzahwe18rx.htm
祝你好运!