Consider this basic multithreading program using pthreads. We have a main thread, creating another thread that does some work.
bool done = false;
mutex m;
condi
The pthread_cond_wait()
call cannot 'spuriously' wake while some other thread is holding the associated mutex. When pthread_cond_wait()
returns successfully, it will have claimed the mutex, so it cannot successfully return until the mutex is available.
In your example, a spurious wake could occur because foo()
can call pthread_cond_wait()
and have the spurious wake occur before child()
ever gets a chance to call pthread_mutex_lock()
in the first place.
Another problem in your example (with the commented code left disabled) has is that it's possible for the pthread_cond_wait()
call to never wake. This scenario can happen if child()
completes all of it's processing before foo()
manages to acquire the mutex. in that scenario, child()
will call pthread_cond_broadcast()
before the main thread is waiting in pthread_cond_wait()
so the main thread will miss the broadcast. Since foo()
never checks done
while holding the mutex, it won't notice that child()
has finished its work.
That's why pthread_cond_wait()
pretty much always has to be performed in a loop that checks the condition.