gpt4 book ai didi

c - 线程是否应该始终使用 while 循环来保存 pthread_cond_wait 语句?

转载 作者:行者123 更新时间:2023-11-30 14:34:51 25 4
gpt4 key购买 nike

据我了解,pthreads 中可能会发生线程的虚假唤醒。以下讨论很有趣且内容丰富:Why does pthread_cond_wait have spurious wakeups? 。我的问题可能很明显,但我想确保我理解正确。当 @acm 声明“...你总是需要检查循环下的谓词”时,意味着我们应该使用 while 循环而不是 for 语句来测试条件,因为前者会重新-测试条件是否为真,而后者将允许看似虚假唤醒的线程继续执行,即使在获得 CPU 时条件可能不再成立?

最佳答案

When @acm makes the statement that "...you already always need to check the predicate under a loop", what is meant is that we should use a while loop to test the condition rather than a for statement,

正如 R 已经说过的,以下之间没有区别:

while (!predicate()) {
pthread_condition_wait(...);
}

for (...; !predicate(); ...) {
pthread_condition_wait(...);
}

您可以使用任一类型的循环编写正确的代码或错误的代码。

关于c - 线程是否应该始终使用 while 循环来保存 pthread_cond_wait 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58793243/

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