C 线程安全队列在IDE';中显示为无输出的问题;s控制台
对于我目前正在处理的项目,我需要一个可以跨多个线程使用的队列,借此机会了解更多关于pthreads的信息,我编写了下面的代码(没有错误检查/与此问题无关的函数)。代码在终端中的运行与预期的一样,但是它在我的IDE(clion)中没有提供任何输出,这使我相信代码中可能存在问题,因为我之前遇到了一个问题,该问题阻止了IDE控制台中的输出,同时在终端中按预期工作。如果它确实有帮助的话,我之前遇到的问题是在从队列推送提前返回时没有解锁互斥锁。我们将非常感谢您在确定问题时提供的任何帮助,谢谢您抽出时间C 线程安全队列在IDE';中显示为无输出的问题;s控制台,c,multithreading,thread-safety,pthreads,posix,C,Multithreading,Thread Safety,Pthreads,Posix,对于我目前正在处理的项目,我需要一个可以跨多个线程使用的队列,借此机会了解更多关于pthreads的信息,我编写了下面的代码(没有错误检查/与此问题无关的函数)。代码在终端中的运行与预期的一样,但是它在我的IDE(clion)中没有提供任何输出,这使我相信代码中可能存在问题,因为我之前遇到了一个问题,该问题阻止了IDE控制台中的输出,同时在终端中按预期工作。如果它确实有帮助的话,我之前遇到的问题是在从队列推送提前返回时没有解锁互斥锁。我们将非常感谢您在确定问题时提供的任何帮助,谢谢您抽出时间 s
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;
}
我可以看到几个问题:
i空的?length==0
是否表示为空?这会导致一些问题,因为在Queue\u pop
方法中,您在不检查队列当时是否为空的情况下减少了长度,这将导致isEmpty和长度之间的不一致
queue->first=item->next
将设置queue->first=NULL->next,这将导致程序崩溃
if(item == queue->last)
{
queue->isEmpty = true;
queue->last = NULL;
}
queue->first = item->next;
1.长度是调试的一个工件,稍后将删除它,因为我不需要知道队列的长度,此外,我了解到在使用
pthread\u cond\u wait
时,应该使用布尔测试,这就是为什么存在isEmpty。这不对吗?2 + 3. 这些都不是问题,正如我的问题所述,我没有发布我的所有代码,只发布与我的问题相关的代码。错误检查、null检查和释放只会延长代码的长度。据我所知,如果我错了,请纠正我。我得到了它。因此,您根本没有使用长度。正确,它只是用于调试目的