Perhaps you want a thread to execute some code only if X > 17, Y is prime, and grandmother is
visiting next Thursday. As long as you can express the condition in a program, you can use it in a
condition variable. A condition variable creates a safe environment for you to test your condition,
sleep on it when false, and be awakened when it might have become true.
It works like this: A thread obtains a mutex (condition variables always have an associated mutex)
and tests the condition under the mutex's protection. No other thread should alter any aspect of the
condition without holding the mutex. If the condition is true, your thread completes its task,
releasing the mutex when appropriate. If the condition isn't true, the mutex is released for you, and
your thread goes to sleep on the condition variable. When some other thread changes some aspect
of the condition (e.g., it reserves a plane ticket for granny), it calls
pthread_cond_signal(), waking up one sleeping thread. Your thread then reacquires the
mutex, reevaluates the condition, and either succeeds or goes back to sleep, depending upon the
The term signal here is distinct from UNIX signals (SIGINT, etc.). Wakeup might be a better term.
Obviously, when a thread sleeps on a condition variable, the mutex must be released (so other
threads can acquire it) and reacquired upon waking. All of this is handled for you by
You must reevaluate the condition! First, the other thread may not have tested the complete
condition before sending the wakeup. Second, even if the condition was true when the wakeup
was sent, it could have changed before your thread got to run. Third, condition variables allow for
spurious wakeups. They are allowed to wake up for no discernible reason whatsoever!
Due to some arcania in the hardware design of modern SMP machines, it proves to be highly
convenient to define them like this. The hardware runs a little faster, and the programmer needs to
reevaluate the condition anyway.
In Figure 6-10, T1, T2, and T3 all evaluated the condition, determined it to be false, and went to
sleep on the condition variable. T4 then came along, changed the condition to true, and woke up
the first of the sleeping threads. T3 was awakened, reevaluated the condition, found it to be true,
and did its thing, releasing the mutex when done. We'll assume that T3 also changed the condition
back to false, so there was no reason to wake any other threads. If T3 hadn't changed the condition,
it should have woken up another thread.
Figure 6-10. Threads Using a Condition Variable
Search WWH :