I understand that spurious wakeups of threads can occur in pthreads. The following discussion was interesting and informative: Why does pthread_cond_wait have spurious wakeups?. My question may be obvious, but I want to make sure I'm understand correctly. 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, since the former will re-test that the condition is true, whereas the latter would allow for the seemingly spuriously woken thread to continue through execution even though the condition may no longer hold when it attains the 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,
As R already said, there is no difference between:
while (!predicate()) {
pthread_condition_wait(...);
}
and
for (...; !predicate(); ...) {
pthread_condition_wait(...);
}
You can write correct code or wrong code using either kind of loop.