gpt4 book ai didi

c - 关于pthread_cond_wait的用法

转载 作者:行者123 更新时间:2023-12-03 12:54:45 24 4
gpt4 key购买 nike

我试图把头放在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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com