我正在尝试了解 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 语句呢?
最佳答案
虚假唤醒。
参见Why does pthread_cond_wait have spurious wakeups?还有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 ...
关于c - 关于pthread_cond_wait的用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41272325/