queueLIFO
是QList
// This function is run by the thread `Producer`.
void *threadProducerFunction (void *arg)
{
Q_UNUSED (arg);
while (1)
{
if (queueLIFO.length () < 10)
{
pthread_mutex_lock (&mutexVariable);
queueLIFO.push_back (1);
pthread_mutex_unlock (&mutexVariable);
}
else
{
pthread_mutex_lock (&mutexVariable);
pthread_cond_wait (&conditionVariable, &mutexVariable);
}
}
return NULL;
}
现在,请考虑此链接中的以下信息:https://computing.llnl.gov/tutorials/pthreads/#ConVarSignal
pthread_cond_wait()
- 当mutex被锁定时应该调用此例程,它会在等待时自动释放互斥锁。收到信号并唤醒线程后,互斥锁将自动锁定以供线程使用。
程序员负责在线程结束时解锁互斥锁。
当从另一个线程接收到信号时,pthread_cond_wait
将锁定此线程使用的互斥锁,这意味着在我的情况下,控件将进入if语句,其中互斥锁已被{{ 1}}(来自else条件)我们现在再次锁定它。
我是否以错误的方式编写了代码逻辑?怎么样?的
答案 0 :(得分:5)
在检查条件之前,您应始终保持锁定。
pthread_mutex_lock (&mutexVariable);
while (queueLIFO.length() >= 10) {
pthread_cond_wait (&conditionVariable, &mutexVariable);
}
queueLIFO.push_back (1);
pthread_mutex_unlock (&mutexVariable);