condition variable – why calling pthread_cond_signal() before calling pthread_cond_wait() is a logical error?

The answer of blaze comes closest, but is not totally clear:
conditional variables should only be used to signal a change in a condition.

Thread 1 checks a condition. If the condition doesn’t meet, he waits on the condition variable until the condition meets. Because the condition is checked first, he shouldn’t care whether the condition variable was signaled:

pthread_mutex_lock(&mutex); 
while (!condition)
    pthread_cond_wait(&cond, &mutex); 
pthread_mutex_unlock(&mutex);

Thread 2 changes the condition and signals the change via the condition variable. He doesn’t care whether threads are waiting or not:

pthread_mutex_lock(&mutex); 
changeCondition(); 
pthread_mutex_unlock(&mutex); 
pthread_cond_signal(&cond)

The bottom line is: the communication is done via some condition. A condition variable only wakes up waiting threads so they can check the condition.

Examples for conditions:

  • Queue is not empty, so an entry can be taken from the queue
  • A boolean flag is set, so the thread wait s until the other thread signal it’s okay to continue
  • some bits in a bitset are set, so the waiting thread can handle the corresponding events

see also pthread example

Leave a Comment