Condition variable

On this page 7

A condition variable is a synchronization primitive that lets one or more threads block until a condition on shared state becomes true, and lets another thread wake them when it changes that state. In concurrency and systems programming, it is always paired with a mutex that protects the shared data, and it replaces wasteful polling loops with efficient sleeping and signaling.

The condition variable itself stores no value and remembers no event. It is a queue of waiting threads, and the actual condition, called the predicate, lives in ordinary variables guarded by the mutex. This separation explains most of its rules and most of the bugs programmers make with it.

How a condition variable works with a mutex

A condition variable works by atomically releasing a mutex and suspending the calling thread in one indivisible step, then reacquiring the mutex before the thread returns from the wait. That atomicity is the whole point: if unlocking and sleeping were separate operations, a signal sent between them would be lost, a failure known as the lost wakeup problem.

The canonical pattern has three parts. The waiting thread locks the mutex, checks the predicate in a while loop, and calls wait while the predicate is false. The signaling thread locks the same mutex, modifies the shared state, and then calls signal or broadcast. Because the waiter rechecks the predicate after every wakeup, the code stays correct even when wakeups arrive for unrelated reasons.

The following table lists the core operations found in nearly every implementation, from POSIX threads to the C++ and Java standard libraries.

OperationWhat it doesPrecondition
WaitReleases the mutex, sleeps, reacquires the mutex on wakeupCaller holds the mutex
Timed waitSame as wait, but returns after a deadlineCaller holds the mutex
Signal (notify one)Wakes at least one waiting thread, if anyMutex usually held, not strictly required
Broadcast (notify all)Wakes every thread currently waitingMutex usually held, not strictly required
Core condition variable operations

Spurious wakeups and the predicate loop

A spurious wakeup is a return from wait that no signal caused, and the POSIX standard and the C++ standard both explicitly permit it. Implementations allow spurious wakeups because forbidding them would make the primitive slower on multiprocessor systems and harder to build on top of kernel facilities such as Linux futexes.

Even without spurious wakeups, a woken thread cannot assume the condition still holds. Between the signal and the moment the waiter reacquires the mutex, another thread may consume the state, for example by taking the single item that was just placed in a queue. For this reason the rule is absolute: always wait inside a loop that rechecks the predicate. C++ offers an overload of wait that accepts a predicate and runs this loop internally.

Wakeup semantics differ between models, and the difference determines how much the waiter can trust a wakeup, as the table shows.

SemanticsWho runs after signalWaiter must recheck predicate
Mesa semanticsSignaler continues; waiter competes for the lock laterYes, always
Hoare semanticsWaiter runs immediately with the lock handed overIn theory no, in practice yes
Hansen variantSignal must be the last action before leavingRarely needed
Monitor semantics and their consequences

Almost every modern library, including pthreads, std::condition_variable, Java monitors and Python threading.Condition, uses Mesa semantics, which is why the predicate loop is mandatory in practice.

A condition variable differs from other primitives in the Concurrency toolbox because it is stateless and coordination-focused: it does not count, own or store anything. Neighboring primitives such as the semaphore and the mutex are often confused with it, yet they answer different questions.

PrimitiveKeeps stateMain purposeTypical misuse
Condition variableNo, the predicate lives elsewhereWait until shared state changesWaiting without a predicate loop
MutexOwner and locked flagMutual exclusion of a critical sectionHolding it while blocking on input
SemaphoreInteger counterCount available resources or permitsUsing it as a lock without ownership
Event or latchSet or unset flagOne-time or manual reset notificationExpecting it to protect data
SpinlockLocked flagVery short critical sectionsSpinning while waiting for a slow condition
Condition variable versus neighboring primitives

A semaphore remembers signals that arrive before anyone waits, whereas a condition variable forgets a signal when no thread is waiting. This is not a defect; it is exactly why the predicate must be stored in shared variables and checked under the mutex rather than inferred from the signal.

Typical use in the producer-consumer pattern

The most common application of condition variables is a bounded buffer, the classic solution to the producer-consumer problem. One mutex protects the queue, and two condition variables express two separate predicates: “the queue is not empty” for consumers and “the queue is not full” for producers.

  1. The consumer locks the mutex and waits on not_empty while the queue length is zero.
  2. The producer locks the mutex, waits on not_full while the queue is at capacity, then pushes an item.
  3. After pushing, the producer signals not_empty; after popping, the consumer signals not_full.
  4. Both sides release the mutex as soon as the queue operation completes.

Using one condition variable per predicate lets each signal target only threads that can make progress. A single shared condition variable also works, but then signaling one thread may wake the wrong kind of waiter, so the code must switch to broadcast to stay correct, which costs extra context switches.

The choice between signal and broadcast follows a simple decision rule.

SituationRecommended callReason
One item added, waiters are interchangeableSignalExactly one waiter can make progress
Shutdown or configuration changeBroadcastEvery waiter must observe the new state
Waiters wait for different predicatesBroadcast or separate variablesA single signal may reach the wrong waiter
Several resources released at onceBroadcast or repeated signalMore than one waiter can proceed
Choosing signal or broadcast

Common mistakes and failure modes

Most condition variable bugs are timing-dependent, so they pass tests and fail under production load. The following list covers the failures that experienced reviewers look for first.

  • Using if instead of while around wait, which breaks on spurious wakeups and stolen state.
  • Changing the predicate without the mutex, which creates a race condition and can lose wakeups.
  • Waiting with different mutexes on the same condition variable, which is undefined behavior in POSIX.
  • Signaling before updating state, so the woken thread sees the old value and sleeps again.
  • Holding a second lock while waiting, which only releases one mutex and invites deadlock.
  • Forgetting a timeout or shutdown flag, leaving threads blocked forever when the program exits.

Performance pitfalls also exist. A broadcast to hundreds of waiters causes a thundering herd, where every thread wakes, contends for the mutex and most go back to sleep. Signaling while holding the mutex can cause a brief wait morphing delay on some platforms, although modern implementations move the waiter directly to the mutex queue to avoid it.

The simple explanation

Imagine a waiting room at a clinic. Patients do not keep walking to the desk every minute to ask whether the doctor is free. They sit down and wait, and the receptionist calls a name when a room opens. A condition variable is that call from the receptionist.

The receptionist does not keep a list of free rooms in her voice; the real information is on the schedule board. When a patient is called, the patient still glances at the board to confirm the room is really free, because someone else may have taken it. In the same way, a waiting thread always rechecks the real data after it wakes up.

How it is used in practice

A team building a log-processing service in C++ runs eight worker threads that read lines from a shared in-memory queue with a capacity of 10,000 entries. A network thread pushes incoming lines into the queue. The first version had workers poll the queue every millisecond, which kept all eight cores busy at about 30 percent even when no traffic arrived.

The engineers replaced polling with one std::mutex and two condition variables, not_empty and not_full. Workers now call wait with a predicate that checks the queue size, and the network thread calls notify_one after each push. For shutdown, a stopping flag is set under the mutex and followed by notify_all, so every worker exits its loop cleanly.

After the change, idle CPU usage dropped to nearly zero, latency stayed below one millisecond at peak load, and the producer stopped overrunning memory because it now blocks when the buffer is full instead of growing it without limit.