http://www.domaigne.com/blog/computing/condvars-signal-with-mutex-locked-or-not/
pthread_mutex_lock(&mutex);
predicate=true;
pthread_cond_signal(&cv); // OR: pthread_mutex_unlock(&mutex);
pthread_mutex_unlock(&mutex); // : pthread_cond_signal(&cv);
Signal with Mutex Locked
On some platforms, the OS performs a context switch to the woken thread right after the signal/broadcast operation, to minimize latency. On a single processor system, this may lead to unnecessary context switches if we signal or broadcast while holding the mutex.
Indeed, consider the scenario shown in figure 1. The thread T2 is blocked on the condition variable. T1 signals the condition while holding the associated mutex. A context switch to T2 occurs and T2 wakes up. But before returning frompthread_cond_wait
, T2 needs to lock the mutex. However that mutex is already hold by T1. As a result T2 blocks (but this time contends for the mutex) and a context switch to T1 occurs. Then T1 unlocks the mutex, and T2 becomes finally runnable. The situation appears to be even worse, if we broadcast the condition variable to several threads.