Part 2 of 7 · 2 min read
The need
In plain words: A diner waits for a table. The diner could ask the host every second whether a table is free, which annoys everyone, or leave a phone number and sit down, to be called when a table is free. The second way is a condition variable. The analogy stops in one place: the host knows by looking at the room, and a thread knows only through the shared data it checks.
Suppose one thread must wait until a shared flag ready becomes 1. With only a mutex, the options are poor:
while (1) { /* polling, holding the lock only briefly */
pthread_mutex_lock(&m);
int r = ready;
pthread_mutex_unlock(&m);
if (r) break; /* the waiter uses a processor all the time */
}
This wastes a processor (the busy waiting of page 2), and a longer pause between checks adds delay. A condition variable is the better tool: a queue on which threads sleep until another thread tells them that the condition may have changed. It is always used together with a mutex, which protects the shared data that the condition is about.
Two operations matter:
- wait: the thread, holding the mutex, calls
pthread_cond_wait(&cond, &m). In one atomic step, the call releases the mutex and puts the thread to sleep on the condition variable. When the thread wakes, the call locks the mutex again before it returns. - signal: another thread, after changing the data, calls
pthread_cond_signal(&cond)to wake one waiting thread, orpthread_cond_broadcastto wake all.
The atomic release-and-sleep is the heart of the matter. If the thread released the mutex first and slept afterwards, a signal could arrive in between and be missed (section 3).
A condition variable holds no value and no memory. If nobody is waiting when it is signalled, the signal is lost. The state lives in the shared data (the flag), not in the condition variable.
Condition variable
A condition variable is a synchronisation object that is used with a mutex and that holds a queue of sleeping threads: a thread waits on it by atomically releasing the mutex and sleeping, and another thread wakes one or all of the sleepers by signalling it after changing the shared data.
Example: a consumer thread waits on not_empty while the queue is empty, and a producer signals not_empty after adding an item.
Check yourself:
1. What does pthread_cond_wait do with the mutex?
2. What happens to a signal sent when nobody waits?
3. Why is polling a poor way to wait?