A bug I keep seeing in code review: the lost wakeup. Condition variables are easy to use wrong in a way that works 999 times out of 1000.
/* waiter */
pthread_mutex_lock(&m);
if (!ready) /* bug 1: if, not while */
pthread_cond_wait(&cv, &m);
pthread_mutex_unlock(&m);
/* signaler */
ready = 1; /* bug 2: no lock held */
pthread_cond_signal(&cv);
Timeline of bug 2:
waiter signaler
lock(m)
check ready == 0
ready = 1
signal(cv) <- nobody is waiting yet
cond_wait(cv, m) <- sleeps forever
The signal happened in the gap between the check and the wait. Nobody was queued, so it vanished. Condition variables have no memory.
Fixes:
- Change the shared state while holding the mutex that the waiter uses. Then the waiter's "check, then wait" is atomic with respect to the change, because
pthread_cond_waitreleases the mutex and starts waiting as one step. - Always wait in a
whileloop:while (!ready) pthread_cond_wait(&cv, &m);. Spurious wakeups are allowed by the standard, and with several waiters another thread may have consumed the condition before you run.
The condition lives in your data, not in the condition variable. The variable is only the doorbell.