c - 关于pthread_cond_wait的用法

标签 c multithreading pthreads condition-variable

我正在尝试了解 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/

相关文章:

c++ - 锁定特定线程

c - 将被零除定义为无穷大

在windows下编译带有unix风格头文件的C程序

c# - 极端线程安全集合

C pthreads send()ing 和 recv()ing 在套接字上。分开工作但没有一起工作。不会退出

linux多线程调度

c - 使用英特尔编译器 (icc) 的四精度数字

c++ - 使用 clang API 编译程序

java - 如何从用作 WatchService 的线程调用主线程中的方法?

c# - 从辅助线程 : is Invoke performance critical? 更新控件