pthread_cond_wait(&cond_var, &mutex);
- The mutex must already be locked by the thread calling pthread_cond_wait
- this call unlocks the mutex
- blocks the calling thread, putting it on the queue for the condition variable
Now assume at least one thread is on the wait queue and another thread modifies the guard condition.
After that thread is through with the guard it can call
pthread_cond_broadcast
and unlock the mutex.
As threads waiting in the call to pthread_cond_wait are woken up they implicitly call pthread_mutex_lock before returning from pthread_cond_wait.
These threads must then check the guard again as it might have been changed by one of the other threads they were awakened.
pthread_mutex_lock(&mutex); while(!guard) { pthread_cond_wait(&cond_var, &mutex); } statement 1; ... statement n; pthread_mutex_unlock(&mutex);