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

Asher Saban picture Asher Saban · Apr 4, 2011 · Viewed 23.2k times · Source

It's written in POSIX threads tutorial https://computing.llnl.gov/tutorials/pthreads/ that it is a logical error.

my question is why it is a logical error?

In my program i need to use these signals, however i cannot guarantee that there will be a thread that will be in _cond_wait state. I tried to test it and nothing happens. Is this can cause unexpected behavior or worse?

thank you!

Answer

stefaanv picture stefaanv · Apr 4, 2011

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