关于pthread_cond_wait的使用

About the usage of pthread_cond_wait

我正在努力思考 pthread 条件变量。 我看过一些使用 pthread_cond_wait 和 pthread_cond_signal 的代码示例,它们看起来都像这样:

while (condition)
{
    // Assume that the mutex is locked before the following call
    pthread_cond_wait(&cond, &mutex);
}

是否有理由在条件上使用 while 循环?为什么不只使用一个 if 语句?

我相信这是因为线程可能在满足条件之前被虚假地唤醒。伙计,谈谈 "gotcha's"。

来自开放组文档:
"Spurious wakeups from the pthread_cond_wait() or pthread_cond_timedwait() functions may occur."

来源:
http://pubs.opengroup.org/onlinepubs/007908775/xsh/pthread_cond_wait.html

虚假唤醒。

Why does pthread_cond_wait have spurious wakeups? and also https://en.wikipedia.org/wiki/Spurious_wakeup:

Spurious wakeup describes a complication in the use of condition variables as provided by certain multithreading APIs such as POSIX Threads and the Windows API.

Even after a condition variable appears to have been signaled from a waiting thread's point of view, the condition that was awaited may still be false. One of the reasons for this is a spurious wakeup; that is, a thread might be awoken from its waiting state even though no thread signaled the condition variable. For correctness it is necessary, then, to verify that the condition is indeed true after the thread has finished waiting. Because spurious wakeup can happen repeatedly, this is achieved by waiting inside a loop that terminates when the condition is true ...

Is there a reason for using a while loop on the condition? why not just use a single if statement?

条件变量背后的想法是暂停线程执行,直到满足给定条件。然而,条件并未内置在变量中——它必须由程序员提供。

如果相关条件已经满足,则无需暂停操作。然而,这里的关键是,当线程恢复时,条件可能 still 不满足,或者是因为在发出信号的条件变量和线程能够继续进行之间发生了某些变化,或者因为线程被虚假唤醒(这是允许发生的,尽管很少发生)。因此,程序会在每次唤醒时再次检查条件,看是否必须继续等待。