previous | start | next

Condition Variables

Condition variables are another means for synchronization in POSIX; they represent queues of threads waiting to be woken by other threads. Though they are rather complicated at first glance, they are even more complicated when you really get into them.

A thread puts itself to sleep and joins the queue of threads associated with a condition variable by calling pthread_cond_wait. When it places this call, it must have some mutex locked, and it passes the mutex as the second argument. As part of the call, the mutex is unlocked and the thread is put to sleep, all in a single atomic step: i.e., nothing can happen that might affect the thread between the moments when the mutex is unlocked and when the thread goes to sleep. Threads queued on a condition variable are released in first-in-first-out order. They are released in response to calls to pthread_cond_signal (which releases the first thread in line) and pthread_cond_broadcast (which releases all threads).

However, before a released thread may return from pthread_cond_wait, it first relocks the mutex. Thus only one thread at a time actually returns from pthread_cond_wait. If a call to either routine is made when no threads are queued on the condition variable, nothing happens -- the fact that a call had been made is not remembered.



previous | start | next