Condition variables
About this lesson
A lock stops two threads from changing shared data at the same time, but it cannot make one thread wait until another has done something. Checking a flag in a loop works, but it wastes the CPU. A condition variable lets the thread sleep instead, and wake when another thread signals that the state has changed. Follow two threads, one that waits and one that signals, through the classic wait-for-done example: the lock, the atomic wait, the signal, and why the check must sit in a while loop. Locks, spinlocks and atomic instructions comes just before this lesson, and the Software lesson on threads and concurrency shows the race that locks prevent.
Waiting by spinning
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.
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.Read the lesson step by step
Waiting by spinning
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.
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.A queue to sleep on
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.
the three parts (C, POSIX threads): int done = 0; state pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER; lock pthread_cond_t c = PTHREAD_COND_INITIALIZER; queue wait(&c, &m) release m and sleep on c, atomically; take m back before returning signal(&c) wake one thread sleeping on c, if any broadcast(&c) wake every thread sleeping on cT1 takes the lock
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.
T1 line 1 pthread_mutex_lock(&m); m held by T1 done 0 c emptyT1 checks done
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.
T1 line 2 while (done == 0) done == 0 true -> enter the loop body m still held by T1Wait: unlock and sleep
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.
T1 line 3 pthread_cond_wait(&c, &m); in one atomic step: m released (free) c queue: T1 (T1 is blocked: asleep) if the two were separate, T2 could set done and signal in the gap, and T1 would sleep forever: a lost wake-up.T2 takes the lock
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 line 1 pthread_mutex_lock(&m); m held by T2 done 0 c queue: T1 (asleep)T2 changes the state
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.
T2 line 2 done = 1; done 0 -> 1 m held by T2Signal wakes T1
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 line 3 pthread_cond_signal(&c); c queue: empty (T1 woken) T1 waiting to re-take m inside wait() m still held by T2 POSIX: signal unblocks at least one waiter; with no waiter it has no effect.T1 gets the lock back
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.
T2 line 4 pthread_mutex_unlock(&m); m free -> held by T1 T1 pthread_cond_wait returns (POSIX: on return the mutex is locked and owned by the calling thread)Check again: a while loop
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 line 2 while (done == 0) done == 0 false -> leave the loop why while, not if (Mesa semantics): another thread may change the state between the signal and the moment T1 runs, and spurious wake-ups are allowed by POSIX.T1 unlocks and goes on
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.
T1 line 4 pthread_mutex_unlock(&m); m free done 1 c empty the whole program prints: parent: begin child parent: endThree rules
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.
the same idea in Python (threading.Condition): import threading done = 0 cv = threading.Condition() # the lock m and the queue c together def child(): # T2 global done with cv: # lock(&m) ... unlock(&m) done = 1 cv.notify() # signal(&c) def join(): # T1 with cv: # lock(&m) while done == 0: cv.wait() # wait(&c, &m) print("child is done") t = threading.Thread(target=child) t.start() join() t.join() prints: child is done
5 quick questions
Choose one answer per question. You can change your choices before checking them.
01Why is spinning (while (done == 0) ;) a poor way for a thread to wait?
Spinning does work in the end, but the waiting thread burns CPU time on every check until the other thread finishes. A condition variable lets it sleep and use no CPU time instead.
02What does pthread_cond_wait(&c, &m) do with the mutex m?
POSIX says wait atomically releases the mutex and blocks, and that on return the mutex is locked and owned by the caller. If the thread slept holding m, the signalling thread could never lock m to change done.
03T2 calls signal(&c) while it still holds m. What happens to the sleeping thread T1 at that moment?
Signal only wakes T1. Inside wait, T1 must re-take the lock, and T2 still holds it. Once T2 unlocks, wait gives m to T1 and returns.
04Why should the check be while (done == 0) and not if (done == 0)?
Real systems use Mesa semantics: a woken thread does not run straight away, so the condition may no longer hold when it does. POSIX also allows spurious wake-ups. Re-checking in a loop is always safe.
05T2 runs first: it sets done = 1 and signals while no thread is waiting. Then T1 runs thr_join. What happens?
A signal with no waiter has no effect: it is not stored. That is fine here, because the state variable done remembers what happened. Without done, T1 would call wait and never be woken.
Glossary
- Condition variable
- A queue where threads can sleep until another thread signals that some state has changed. It is always used together with a lock and a state variable.
- Mutex
- A lock that only one thread can hold at a time (short for mutual exclusion). Here, whoever holds m may read or change done.
- State variable
- The shared variable that records the condition a thread waits for, such as done. The sleeping, waking and locking are all built around it.
- Wait
- Release the lock and sleep on the condition variable, in one atomic step; take the lock back before returning. In POSIX C: pthread_cond_wait.
- Signal
- Wake one thread sleeping on a condition variable, if any. With no sleeper it does nothing. Broadcast wakes all of them.
- Spinning
- Waiting by checking a condition over and over in a loop. Simple, but it keeps the CPU busy the whole time.
- Mesa semantics
- The usual rule for condition variables: a woken thread runs later, not at once, so it must check the condition again.
- Spurious wake-up
- A return from wait that no signal asked for. POSIX allows it, which is another reason to wait in a while loop.
Notes and sources
- 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.
- POSIX says signal unblocks at least one waiting thread, and broadcast unblocks all of them. Python's notify() wakes one thread by default and raises RuntimeError if the caller does not hold the lock.
- Waking a thread without handing it the lock at once is called Mesa semantics, after the Mesa system at Xerox PARC. The other kind, Hoare semantics, runs the woken thread immediately. Almost every real system uses Mesa semantics, which is why the check sits in a while loop.
- On Linux, thread libraries build mutexes and condition variables on futexes. The kernel is only involved when threads actually contend: here, to put T1 to sleep and to wake it. xv6, the teaching kernel from MIT, has the same pair inside the kernel: sleep(chan, lock) and wakeup(chan).
- R. and A. Arpaci-Dusseau, Operating Systems: Three Easy Pieces, ch. 30: Condition Variables
- POSIX (Linux man-pages): pthread_cond_wait(3p)
- POSIX (Linux man-pages): pthread_cond_broadcast(3p) and pthread_cond_signal
- Python documentation: threading, Condition objects
- Berkeley CS162, Lecture 9: Semaphores, Monitors and Readers/Writers
- MIT 6.1810, lecture notes: Coordination (sleep and wakeup)
- Linux man-pages: futex(7)
Quiz Unlocks after the last step.