线程是否应该始终使用 while 循环来保存 pthread_cond_wait 语句?
Should a thread always use a while loop to hold a pthread_cond_wait statement?
我了解线程的虚假唤醒可能发生在 pthread 中。以下讨论很有趣且内容丰富: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(...);
}
您可以使用任何一种循环编写正确的代码或错误的代码。
我了解线程的虚假唤醒可能发生在 pthread 中。以下讨论很有趣且内容丰富: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(...);
}
您可以使用任何一种循环编写正确的代码或错误的代码。