Why sleep, not spin
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.
A condition variable is a queue where a thread can sleep until another thread signals that something changed. It is always used with a lock, here the mutex m, and a state variable, here done.
T1 waits
T1 runs first. Line 1 locks the mutex m, so T1 now holds the key. While T1 holds it, no other thread can lock m, so no one can change done while T1 looks at it.
Line 2 reads done. It is 0, so T2 has not finished yet and T1 must wait. T1 still holds the lock, so done cannot change between this check and the wait.
wait(&c, &m) does two things in one atomic step: it releases the lock and puts T1 to sleep on the queue of c. No signal can slip in between, and a sleeping thread uses no CPU time.
T2 signals
Now T2 runs. Its lock(&m) succeeds at once, because wait gave the lock back. If T1 had gone to sleep still holding the lock, T2 could never get in, and both threads would be stuck.
T2 sets done to 1 while it holds the lock. This is the change T1 is waiting for. It is stored in a variable, so it stays true however late anyone looks.
signal(&c) wakes one thread sleeping on c, so T1 leaves the queue. But T1 cannot return from wait yet: wait must take the lock back first, and T2 still holds it.
T2 unlocks m. Now wait takes the lock for T1 and returns, so T1 finishes line 3 holding the lock, just as it was before it went to sleep.
The rules
The while loop sends T1 back to line 2 to check done again. It is 1, so the loop ends. A wake-up only hints that the state changed, and threads can even wake for no reason, so always check again.
T1 unlocks m and carries on. It waited without spinning: it slept on c, used no CPU time while asleep, and woke only after T2 had set done to 1.
Hold the lock when you change the state, wait or signal. Wait inside a while loop. Keep the condition in a state variable: a signal sent when no thread is waiting is simply lost.
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.