To quote the man page:
When using condition variables there is always a Boolean predicate involving shared variables associated with each condition wait that is true if the thread should proceed. Spurious wakeups from the pthread_cond_timedwait() or pthread_cond_wait() functions may occur. Since the return from pthread_cond_timedwait() or pthread_cond_wait() does not imply anything about the value of this predicate, the predicate should be re-evaluated upon such return.
So, pthread_cond_wait
can return even if you haven't signaled it. At first glance at least, that seems pretty atrocious. It would be like a function which randomly returned the wrong value or randomly returned before it actually reached a proper return statement. It seems like a major bug. But the fact that they chose to document this in the man page rather than fix it would seem to indicate that there is a legitimate reason why pthread_cond_wait
ends up waking up spuriously. Presumably, there's something intrinsic about how it works that makes it so that that can't be helped. The question is what.
Why does pthread_cond_wait
return spuriously? Why can't it guarantee that it's only going to wake up when it's been properly signaled? Can anyone explain the reason for its spurious behavior?
Best Answer
There are at least two things 'spurious wakeup' could mean:
pthread_cond_wait
can return from the call even though no call topthread_call_signal
orpthread_cond_broadcast
on the condition occurred.pthread_cond_wait
returns because of a call topthread_cond_signal
orpthread_cond_broadcast
, however after reacquiring the mutex the underlying predicate is found to no longer be true.But the latter case can occur even if the condition variable implementation does not allow the former case. Consider a producer consumer queue, and three threads.
pthread_cond_wait
, and blocks in the call awaiting signal/broadcast.So since you already always need to check the predicate under a loop, it makes no difference if the underlying condition variables can have other sorts of spurious wakeups.