【发布时间】:2015-03-12 00:35:56
【问题描述】:
对于我目前正在进行的项目,我需要一个可以跨多个线程使用的队列,借此机会了解更多关于 pthread 的信息我编写了下面提供的代码(没有错误检查/与这个问题)。代码在终端中按预期运行,但是它在我的 IDE(clion)中没有提供任何输出,这让我相信代码中的某个地方可能存在问题,因为我之前遇到了一个问题,阻止了 IDE 控制台中的输出在终端按预期工作时。如果它确实有帮助,我之前遇到的问题是从 Queue_push 提前返回时没有解锁互斥锁。非常感谢您在确定问题方面的任何帮助,感谢您抽出宝贵时间。
struct queue
{
QueueItem *first;
QueueItem *last;
pthread_mutex_t queueMutex;
pthread_cond_t isEmptyCondition;
bool isEmpty;
};
void Queue_push(Queue *queue, void *element)
{
QueueItem *item;
QueueItem_create(&item);
item->value = element;
pthread_mutex_lock(&queue->queueMutex);
if(queue->isEmpty == true)
{
queue->last = item;
queue->first = item;
queue->isEmpty = false;
pthread_mutex_unlock(&queue->queueMutex);
pthread_cond_broadcast(&queue->isEmptyCondition);
return;
}
queue->last->next = item;
queue->last = item;
pthread_mutex_unlock(&queue->queueMutex);
}
void *Queue_pop(Queue *queue)
{
pthread_mutex_lock(&queue->queueMutex);
while(queue->isEmpty == true) {
pthread_cond_wait(&queue->isEmptyCondition, &queue->queueMutex);
}
QueueItem *item = queue->first;
if(item == queue->last)
{
queue->isEmpty = true;
queue->last = NULL;
}
queue->first = item->next;
pthread_mutex_unlock(&queue->queueMutex);
return item->value;
}
【问题讨论】:
标签: c multithreading thread-safety pthreads posix