ENع
←Condition variables
Lesson 20 · Synchronisation

Condition variables

14 min12 steps5 questionsIntermediate
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.

You'll learn to

Tick what you feel confident about. These self-checks do not affect your lesson score.

Fig 20 · Interactive
01 / 12

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.
Loading figure…
or ← →
Read the lesson step by step
  1. 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.
  2. 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 c
  3. T1 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      empty
  4. T1 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 T1
  5. Wait: 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.
  6. 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)
  7. 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 T2
  8. Signal 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.
  9. 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)
  10. 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.
  11. 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: end
  12. Three 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

Quiz Unlocks after the last step.