8.9 Condition Variables and Semaphores

CONCURRENCYSTATUS: DEVELOPINGLEVEL: INTERMEDIATEREVIEWED: 2026-10-21
Before this page Mutexes

8.9.1 Motivation

A mutex serializes access to a resource. A condition variable lets a thread sleep until another thread changes the state that the mutex protects. A semaphore is a counter of permits: a thread takes one before it continues and gives it back when it is done. A condition variable always works together with a mutex, while a semaphore carries its own counter and needs no separate lock.

8.9.2 The problem

Imagine a work queue protected by a mutex. A worker thread loops, checking if work is available.

loop:
  lock(queue_mutex)
  if queue is not empty:
    work = dequeue()
    unlock(queue_mutex)
    do_work(work)
  else:
    unlock(queue_mutex)
    sleep(1 millisecond)  // Spin-sleep loop

This works, but it costs in two directions. An idle worker still wakes about a thousand times per second to lock the queue and find it empty, and each wakeup is a trip through the scheduler. When work does arrive, it can sit in the queue for up to a millisecond before the worker notices. A shorter sleep cuts the delay and adds wakeups; a longer one does the opposite.

A condition variable removes the polling. The worker waits on a condition, “queue not empty”, and blocks without using CPU. When work arrives, the thread that added it wakes the worker, which then checks the queue again.

8.9.3 Mental model

A condition variable is a place where threads wait for a change to state that a mutex protects. The waiter says: “I am waiting for a condition.” The notifier says: “The condition is true now.” The waiter wakes and checks.

A condition variable is useless without a mutex, and the reason is atomicity. The waiter has to check the condition and go to sleep as one indivisible step. Split them and the wake-up can land in the gap. Imagine:

  1. Waiter checks: queue is empty.
  2. Notifier adds work to queue.
  3. Notifier calls notify() on the condition variable.
  4. Waiter calls wait() on the condition variable.

The notify happened before the wait. The waiter is now blocked forever, even though work is ready. This is the lost-wakeup problem.

A mutex closes the gap. The waiter holds the mutex from the check until it calls wait(), and wait() releases the mutex and blocks the thread in one atomic step. The notifier must acquire the same mutex to add work, so it cannot slip in between the check and the sleep.

8.9.4 Mechanism

The condition variable protocol

  1. Waiter acquires the mutex.
  2. Waiter checks the condition (e.g., queue not empty).
  3. If false, waiter calls wait(condition_variable, mutex).
  4. wait() releases the mutex and blocks the waiter.
  5. Waiter is now parked in the kernel.
  6. Notifier acquires the mutex, changes state (adds work), calls notify().
  7. notify() wakes the waiter.
  8. Waiter reacquires the mutex and returns from wait().
  9. Waiter checks the condition again (important: check again, do not assume it is true).
  10. If true, proceed. If false, go to step 3.

The step people leave out is step 9, the recheck after waking. There are two reasons for it. First, another thread can take the mutex between the notify and the waiter’s return from wait(), and consume the work, so the condition is false again by the time the waiter runs. Lampson and Redell’s Mesa monitors made this the defined behavior: a notify is a hint, and the waiter must check again each time it resumes. Second, spurious wakeups are allowed: wait() can return when no thread called notify(). POSIX permits them for pthread_cond_wait(), citing multiprocessor implementations, and Rust’s Condvar::wait documents the same. Either way, a return from wait() says nothing about the condition, so the waiter checks it in a loop.

lock(condition_mutex)
while not condition:       // while, not if
  wait(condition_var, condition_mutex)
do_work()
unlock(condition_mutex)

Semaphores

A semaphore is a different primitive. It holds a count instead of waiting on an arbitrary condition. A thread can increment the counter (post) or decrement it (wait). If the counter is 0, wait blocks. If the counter is greater than 0, wait decrements and proceeds.

semaphore:
  counter = 0

post(semaphore):
  counter = counter + 1
  if any threads are blocked on this semaphore:
    wake one

wait(semaphore):
  if counter > 0:
    counter = counter - 1
    return
  else:
    block until counter > 0
    counter = counter - 1
    return

Semaphores count permits. A semaphore initialized to 1 is a binary semaphore. It acts like a lock, with one difference: it has no owner, so a thread other than the one that waited may post it.

A semaphore initialized to N permits N threads to proceed concurrently. This is useful for resource pooling: N printers, N database connections. A thread acquires a permit before using a resource. When done, it releases the permit. Other threads waiting for permits wake.

Condition variable vs semaphore

A condition variable waits for a boolean condition. A semaphore waits for a permit to be available.

Condition variables: “I am waiting for the queue to be non-empty.”

Semaphores: “I am waiting for a free database connection.”

Condition variables pair with a mutex and a state. Semaphores are standalone (though they have internal atomicity).

POSIX provides both, as pthread_cond_t and sem_t. Rust’s standard library provides Condvar but no semaphore. A counting semaphore in Rust comes from a crate, such as tokio::sync::Semaphore for async code, or from a Mutex<usize> paired with a Condvar.

8.9.5 A simple example: producer-consumer

A producer thread adds items to a queue. A consumer thread removes items.

queue = []
queue_lock = new_mutex()
not_empty = new_condition_variable()

producer():
  for i in 1 to 1000:
    lock(queue_lock)
    queue.append(i)
    notify(not_empty)  // Signal: queue is not empty
    unlock(queue_lock)

consumer():
  loop:
    lock(queue_lock)
    while queue is empty:
      wait(not_empty, queue_lock)  // Release lock, wait, reacquire
    item = queue.pop()
    unlock(queue_lock)
    process(item)

The producer appends and notifies. The consumer waits if the queue is empty. When the producer adds an item and notifies, the consumer wakes, reacquires the lock, pops the item, and processes it. While the queue is empty, the consumer uses no CPU at all.

8.9.6 Spurious wakeups: why you must use while, not if

The waiter must recheck after waking, because POSIX and Rust both permit spurious wakeups and because another thread may have taken the work first.

// WRONG: uses if
lock(condition_mutex)
if not condition:
  wait(condition_var, condition_mutex)
do_work()
unlock(condition_mutex)

// CORRECT: uses while
lock(condition_mutex)
while not condition:
  wait(condition_var, condition_mutex)
do_work()
unlock(condition_mutex)

In the WRONG version, a spurious wakeup, or a waiter that lost the race for the work, runs do_work() while the condition is false.

In the CORRECT version, a spurious wakeup causes the loop to check the condition again. If false, it waits again.

8.9.7 Broadcast and notify_one

A condition variable can wake one waiter or all waiters.

notify_one(): Wake one waiter. Useful when only one waiter needs to proceed.

notify_all() (or broadcast): Wake all waiters. Useful when the condition change affects many waiters.

Overusing notify_all() wastes CPU: all waiters wake, reacquire the lock, check the condition, and if false, block again. Using notify_one() when only one waiter cares is more efficient.

8.9.8 Semaphores for resource pooling

A semaphore initialized to N permits can limit access to N resources.

database_connections = semaphore(3)  // At most 3 concurrent

worker_thread():
  wait(database_connections)    // Acquire a permit
  connection = open_connection()
  do_query(connection)
  connection.close()
  post(database_connections)    // Release a permit

At most 3 threads can hold database connections concurrently. Other threads wait on the semaphore. When a thread releases the permit, one waiting thread wakes.

8.9.9 Tradeoffs

Condition variables are expressive but easy to misuse. A missing while loop gives a bug that appears only under contention or after a spurious wakeup, so tests rarely catch it.

Semaphores are simpler to understand but less flexible. They count but do not express complex conditions.

Waking a blocked thread costs a context switch with either primitive.

sequenceDiagram
  participant W as waiter
  participant M as mutex
  participant N as notifier
  W->>M: lock
  W->>W: check condition: false
  W->>M: wait() unlocks, waiter parks
  N->>M: lock
  N->>N: change the state
  N-->>W: notify() wakes the waiter
  N->>M: unlock
  W->>M: wait() relocks, then returns
  W->>W: check again: true, proceed

Condition variable protocol. Waiter checks, blocks, and waits. Notifier changes state and wakes. Waiter reacquires and rechecks.

Further reading

Where this appears

  • threaded-r Cross-interpreter task queues and work-stealing structures benefit from condition variables for efficient worker parking.

Where to go next

Back to top