Part 4 of 7 · 2 min read
Lost wakeup
Think of it this way. A person who leaves the room just before the doorbell rings does not hear it, and nobody rings again. A condition variable keeps no memory, so a signal sent when nobody waits is simply lost. A thread that waits afterwards, without checking whether the event has already happened, sleeps for ever.
In plain words: A test: the signaller sets a flag and signals at once, but the waiter arrives 100 ms later. Each version waits with a time limit of 500 ms, so that the lost signal shows as a timeout instead of a hang:
signal before the wait:
waiter ignoring the flag: timed out after 500 ms, the signal was lost
waiter checking the flag: returned at once
The version without the check goes to sleep, because the only signal is in the past. The version that tests ready before waiting sees the flag already set, and never waits. So the flag is the memory, and the condition variable is the doorbell. The standard rule follows:
Always change the shared state under the mutex, then signal; always test the state under the mutex, and wait only if the state says so.
Two typical mistakes cause lost wakeups. One: a wait without a loop or a test (pthread_cond_wait called unconditionally). Two: changing the shared data without holding the mutex, so the waiter tests the flag (0), the signaller then sets it and signals, and the waiter then goes to sleep, all before the waiter's release-and-sleep step. Holding the mutex over both the test and the wait, and over the change and the signal, closes that gap.
Lost wakeup
A lost wakeup is the failure in which a signal is sent before the target thread is waiting, or in the gap between its test and its sleep, so the thread never receives it and may wait for ever.
Example: a thread that calls pthread_cond_wait without first testing the flag, after the flag was already set and signalled, sleeps until its timeout.
Check yourself: 1. Why did the version that tested the flag return at once? 2. What is the memory in a condition-variable design? 3. Name the two typical causes of a lost wakeup.