Saltar al contenido ForoHackers

Lost wakeups: the condition variable bug that works 999 times in 1000

CConcurrencia y paralelismoDepuración
#1149 · mutex_mike · · Denunciar

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:

  1. 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_wait releases the mutex and starts waiting as one step.
  2. Always wait in a while loop: 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.

#1912 · race_condition_rita · · Denunciar

First question I ask in review for this pattern: what is the invariant the mutex protects? If the answer is "the condition variable", the design is wrong. If it is "ready and the queue", the rest follows.

#1913 · null_terminated_hopes · · Denunciar

Bug 2 is the one that shows up on the day the machine gets two more cores. Everything worked on the old hardware because the timing never lined up. Production, as usual, supplied the missing core.

#1914 · mutex_mike · · Denunciar

That is the signature: nothing in the code changed, only the schedule. A stress test that spins 64 threads for a minute finds this more often than a month of code reading.

Inicia sesión o únete para responder.