0

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?

soporific312
  • 167
  • 10
  • 1
    I don't understand what distinction you're making between a while loop and a for loop. They're just different syntactical sugar for ifs and gotos. – R.. GitHub STOP HELPING ICE Nov 11 '19 at 01:10
  • The highlighted segment in @Employed Russian's answer is the distinction I was making. Such a condition should always be checked under a while loop rather than a for loop, though you can write a for loop to essentially be a while loop. Looking back at this question, it is rather obvious but I'll leave it up since its already resolved. – soporific312 Jan 02 '20 at 00:03

1 Answers1

1

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.

Employed Russian
  • 199,314
  • 34
  • 295
  • 362