OSF DCE Application Development Guide--Core Components
Programming with Threads
8.7 Signaling a Condition Variable
When you are signaling a condition variable and that signal may cause the condition
variable to be deleted, it is recommended that you signal or broadcast with the mutex
locked.
The recommended coding for signaling a condition variable appears at the end of this
chapter. The following two C code fragments show coding that is not recommended.
The following C code fragment is executed by a releasing thread:
pthread_mutex_lock (m);
/* Change shared variables to allow */
/* another thread to proceed */
pthread_mutex_unlock (m); <---- Point A
pthread_cond_signal (cv); <---- Statement 1
The following C code fragment is executed by a potentially blocking thread:
pthread_mutex_lock (m);
while (!predicate ...
pthread_cond_wait (cv, m);
pthread_mutex_unlock (m);
Note: It is possible for a potentially blocking thread to be running at Point A
while another thread is interrupted. The potentially blocking thread can
then see the predicate true and therefore not become blocked on the
condition variable.
Signaling a condition variable without first locking a mutex is not a problem. However,
if the released thread deletes the condition variable without any further synchronization
at Point A, then the releasing thread will fail when it attempts to execute Statement 1
because the condition variable no longer exists.
This problem occurs when the releasing thread is a worker thread and the waiting thread
is the boss thread, and the last worker thread tells the boss thread to delete the variables
that are being shared by boss and worker.
The following C code fragment shows the recommended coding for signaling a
condition variable while the mutex is locked:
pthread_mutex_lock (m);
/* Change shared variables to allow */
/* some other thread to proceed */
pthread_cond_signal (cv); <---- Statement 1
pthread_mutex_unlock (m);
124245 Tandem Computers Incorporated 8− 13










