Part 3 of 7 · 2 min read
The protocol
In plain words: The standard pattern has a waiting side and a signalling side. A trace shows the order of events, with a flag ready, a mutex m and a condition variable c:
/* waiting side */ /* signalling side */
pthread_mutex_lock(&m); pthread_mutex_lock(&m);
while (!ready) ready = 1;
pthread_cond_wait(&c, &m); pthread_cond_signal(&c);
/* use the data */ pthread_mutex_unlock(&m);
pthread_mutex_unlock(&m);
| Step | Waiter | Signaller | ready |
Mutex |
|---|---|---|---|---|
| 1 | locks, finds ready = 0 |
0 | waiter | |
| 2 | cond_wait: releases the mutex and sleeps |
0 | free | |
| 3 | locks, sets ready = 1 |
1 | signaller | |
| 4 | signals (wakes the waiter) | 1 | signaller | |
| 5 | wakes, but must lock the mutex: blocked | 1 | signaller | |
| 6 | unlocks | 1 | free | |
| 7 | locks the mutex, cond_wait returns; the loop tests ready: 1, so it leaves |
1 | waiter |
The points to see: the mutex is released while the waiter sleeps (step 2), so the signaller can get in (step 3). The woken thread must lock the mutex again before it can continue (steps 5 to 7), so it does not run at once, and by the time it does run the data may have changed. The woken thread must therefore test the condition again, which is why the wait sits in a loop.
A reason beyond this: the standard allows a spurious wakeup, a return from pthread_cond_wait although nobody signalled. It is rare, but it can occur, since an implementation can be simpler and faster if it may wake a thread more often than necessary. A loop that rechecks the real condition handles it, and also handles every other case in which the condition is no longer true.
Spurious wakeup
A spurious wakeup is the return of a thread from a condition-variable wait although no thread has signalled or broadcast, which the standard permits, and which is why a waiting thread must always retest its condition in a loop.
Example: a waiter that returns from pthread_cond_wait with ready still 0 goes round the loop and waits again.
Check yourself: 1. Why can the signaller lock the mutex in step 3? 2. Why does the woken thread not run immediately? 3. What does the loop around the wait handle?