mutex mfreedone0cond var cempty1lock(&m);2while (done == 0)3 wait(&c, &m);4unlock(&m);1lock(&m);2done = 1;3signal(&c);4unlock(&m);CPUT2T101
Back: the mutex m, the state variable done, the condition variable c (its queue)Front: the code of thread T1 (waits) and thread T2 (signals), and the CPUTokens: the key is the lock; T1 sleeps on c; the envelope is the signalAt the back: the mutex m (the key rests on it when the lock is free), the state variable done, and the condition variable c, a bench where sleeping threads queue. In front: the code of thread T1 and thread T2, and the CPU. T1 takes the key, finds done is 0, and in one move gives the key back and falls asleep on c. T2 takes the key, sets done to 1 and signals; T1 wakes but waits for the key until T2 unlocks, then checks done again and goes on. The cards use short names. In C with POSIX threads, lock is pthread_mutex_lock, unlock is pthread_mutex_unlock, wait is pthread_cond_wait and signal is pthread_cond_signal. The full program is the parent-and-child example from OSTEP chapter 30.

Why sleep, not spin

  1. Thread T1 needs to wait until thread T2 sets done to 1. The simplest way is to spin: check done again and again in a loop. It works, but T1 burns CPU time doing nothing useful.

T1 waits

T2 signals

The rules

What happens

;; step 1/12 · spin
the spin version (OSTEP fig. 30.2):

while (done == 0)
    ;  /* spin: check again, and again ... */

T1 runs this loop on the CPU the whole time;
every check finds done == 0 until T2 finishes.
CPU time used while waiting: all of it.

The cards use short names. In C with POSIX threads, lock is pthread_mutex_lock, unlock is pthread_mutex_unlock, wait is pthread_cond_wait and signal is pthread_cond_signal. The full program is the parent-and-child example from OSTEP chapter 30. The figure shows the case where T1 runs first. If T2 runs first, it sets done to 1 and signals with no one asleep, so the signal has no effect; T1 then finds done is 1 and never waits. The state variable is what makes both orders work.