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?
pthread_cond_(timed)wait
: "If a signal is delivered ... the thread resumes waiting for the condition variable as if it was not interrupted, or it shall return zero due to spurious wakeup". Other blocking functions indicateEINTR
when interrupted by a signal (e.g.read
), or are required to resume (e.g.pthread_mutex_lock
). So if there were no other reasons for spurious wake-up,pthread_cond_wait
could have been defined like either of those. – Getupandgo