[Return to Bookshelf] [Contents] [Previous Section] [Next Section] [Index] [Help]


3.6.4 Signaling a Condition Variable

When you are signaling a condition variable and that signal might cause the condition variable to be deleted, signal or broadcast the condition variable with the mutex locked.

The following C code fragment is executed by a releasing thread (Thread A):

pthread_mutex_lock (m);

... /* Change shared variables to allow another thread to proceed */

predicate = TRUE;
pthread_mutex_unlock (m);
                            1
pthread_cond_signal (cv);   2

The following C code fragment is executed by a potentially blocking thread (Thread B):

pthread_mutex_lock (m);
while (!predicate )
      pthread_cond_wait (cv, m);

pthread_mutex_unlock (m);
pthread_cond_destroy (cv);

  1. If Thread B is allowed to run while Thread A is at this point, it finds the predicate true and continues without waiting on the condition variable. Thread B might then delete the condition variable with the pthread_cond_destroy routine before Thread A resumes execution.

  2. When Thread A executes this statement, the condition variable does not exist and the program fails.

The previous code fragments also demonstrate a race condition. The program depends on a sequence of events among multiple threads, but it does not enforce the desired sequence. Signaling the condition variable while holding the associated mutex eliminates the race condition. That prevents Thread B from deleting the condition variable until after Thread A has signaled it.

This problem can occur when the releasing thread is a worker thread and the waiting thread is a boss thread, and the last worker thread tells the boss thread to delete the variables that are being shared by boss and worker.

Code the signaling of a condition variable with the mutex locked as follows:

pthread_mutex_lock (m);
... /* Change shared variables to allow some other thread to proceed */

pthread_cond_signal (cv);
pthread_mutex_unlock (m);



[Return to Bookshelf] [Contents] [Previous Section] [Next Section] [Index] [Help]