# Condition variables and waiting

> A condition variable lets a thread sleep until some state guarded by a mutex changes, and it is only correct when the waiter rechecks a predicate and the notifier changes that predicate under the mutex. C++20 adds atomic waits, semaphores, latches and barriers for the cases a condition variable handles clumsily.

- **Source:** C++ Atlas (https://cppatlas.com/topics/condition-variables-and-waiting)
- **Track:** Concurrency
- **Estimated reading time:** 14 minutes
- **ISO C++ clauses:** [thread.condition] (https://eel.is/c++draft/thread.condition), [thread.condition.condvar] (https://eel.is/c++draft/thread.condition.condvar), [thread.condition.condvarany] (https://eel.is/c++draft/thread.condition.condvarany), [thread.condvarany.intwait] (https://eel.is/c++draft/thread.condvarany.intwait), [thread.req.timing] (https://eel.is/c++draft/thread.req.timing), [atomics.wait] (https://eel.is/c++draft/atomics.wait), [thread.sema] (https://eel.is/c++draft/thread.sema), [thread.latch] (https://eel.is/c++draft/thread.latch), [thread.barrier] (https://eel.is/c++draft/thread.barrier)
- **cppreference links:** [std::condition_variable](https://en.cppreference.com/w/cpp/thread/condition_variable), [std::condition_variable::wait](https://en.cppreference.com/w/cpp/thread/condition_variable/wait), [std::condition_variable_any::wait](https://en.cppreference.com/w/cpp/thread/condition_variable_any/wait), [std::condition_variable::wait_for](https://en.cppreference.com/w/cpp/thread/condition_variable/wait_for), [std::atomic<T>::wait](https://en.cppreference.com/w/cpp/atomic/atomic/wait), [std::counting_semaphore, std::binary_semaphore](https://en.cppreference.com/w/cpp/thread/counting_semaphore), [std::latch](https://en.cppreference.com/w/cpp/thread/latch), [std::barrier](https://en.cppreference.com/w/cpp/thread/barrier)
- **Prerequisites:** mutexes-and-locks, threads-and-jthread, atomics-and-memory-ordering, chrono

## The one idea

A condition variable does not hold a condition. It holds a queue of sleeping threads, and a notification is a nudge that says "something may have changed, go and look". Notifications are not stored: notifying a condition variable that nobody is waiting on does nothing at all. The condition itself is ordinary state, the *predicate*, guarded by a mutex, and the only correct way to use a condition variable is to check the predicate under that mutex, sleep if it is false, and check again on every wake.

> **Mental model.** The mutex protects the predicate, the predicate is the truth, and the condition variable is just an efficient way to sleep between checks. If your code would still be correct with `wait` replaced by "unlock, yield, relock", it is correct with `wait`.

## What wait actually does

`std::condition_variable::wait(lock)` takes a `std::unique_lock<std::mutex>` that the caller holds. It atomically releases the mutex and blocks. When it is unblocked, it reacquires the mutex before returning, so the caller always holds the lock again afterwards. Unblocking happens on `notify_one`, `notify_all`, or *spuriously*, for no reason at all. The standard permits spurious wakeups because some platforms' native primitives have them and because they make the implementation simpler.

The overload that takes a predicate, `wait(lock, pred)`, is exactly `while (!pred()) wait(lock);`. It checks before the first sleep, so if the predicate is already true, it returns without blocking and without needing any notification. Use it everywhere; the bare overload is a building block.

```cpp
#include <condition_variable>
#include <mutex>
#include <queue>

class Channel {
  std::mutex m_;
  std::condition_variable cv_;
  std::queue<int> q_;
public:
  void push(int v) {
    { std::lock_guard lk(m_); q_.push(v); }   // change the predicate under the mutex
    cv_.notify_one();
  }
  int pop() {
    std::unique_lock lk(m_);
    cv_.wait(lk, [&] { return !q_.empty(); });   // loop handles spurious wakeups
    int v = q_.front();
    q_.pop();
    return v;
  }
};
```

`std::condition_variable` accepts only `std::unique_lock<std::mutex>`, which lets implementations map it directly onto the platform's primitive. A `lock_guard` cannot be passed, because `wait` must unlock and relock it. All threads waiting on one condition variable at the same time must use the same mutex.

> **Standardese.** [thread.condition.condvar] makes it a precondition of `wait` that the lock is owned by the calling thread and that every concurrently waiting thread supplied the same mutex. It also says that if `wait` cannot reacquire the lock, `std::terminate` is called. [thread.condition] requires notifications and the parts of each wait to behave as if they happen in a single total order consistent with happens-before.

## Lost wakeups, and why the predicate needs the mutex

The atomic unlock-and-block step exists to close one gap: between the waiter's check of the predicate and its going to sleep, nobody may slip in a change and a notification. That guarantee only works if the notifier changes the predicate while holding the same mutex. Making the flag atomic is not a substitute.

```cpp
#include <atomic>
#include <condition_variable>
#include <mutex>

std::mutex m;
std::condition_variable cv;
std::atomic<bool> ready{false};

void waiter() {
  std::unique_lock lk(m);
  cv.wait(lk, [] { return ready.load(); });   // may sleep forever
}

void setter() {
  ready = true;      // not under m: no data race, but...
  cv.notify_one();   // ...this can land between waiter's check and its sleep
}
```

Here is the losing interleaving. The waiter takes the mutex and sees `ready == false`. Before it blocks, the setter stores `true` and notifies; nobody is waiting yet, so the notification evaporates. The waiter then blocks, and nothing will ever wake it. If the setter had locked `m` around the store, it could not have run between the check and the block, because the waiter holds `m` for that whole stretch. The lock can be released before `notify_one` is called; it only has to cover the change.

## Notify inside or outside the lock

Both placements are correct if the predicate was changed under the mutex. Notifying after unlocking avoids waking a thread that will immediately block again on the mutex the notifier still holds, though many implementations already avoid that cost. Notifying while still holding the lock has one real advantage: object lifetime.

The destructor of a condition variable requires that no thread is blocked on it, and of course nobody may call `notify_one` on a destroyed one. If the waiter owns the condition variable, it may see the predicate become true, return, and destroy the condition variable while the notifier is still about to call `notify_one`. Notifying under the lock prevents this, because the waiter cannot return from `wait` until it reacquires the mutex, which is after the notification has finished.

```cpp
#include <condition_variable>
#include <mutex>
#include <thread>

void run() {
  std::mutex m;
  std::condition_variable cv;
  bool done = false;
  std::thread([&] {
    std::lock_guard lk(m);
    done = true;
    cv.notify_one();   // under the lock: run() cannot return before this finishes
  }).detach();
  std::unique_lock lk(m);
  cv.wait(lk, [&] { return done; });
}   // cv and m are destroyed here
```

Move the `notify_one` after the lock is released and this function may destroy `cv` while the detached thread is still about to use it, which is undefined behavior. Detaching is rarely a good idea, as threads-and-jthread explains, but the same pattern appears whenever a waiter owns the synchronization object.

## condition_variable_any and stop tokens

`std::condition_variable_any` works with any *Cpp17BasicLockable*, such as a `std::shared_lock`, a `std::unique_lock` over a mutex type other than `std::mutex`, or your own type. It is usually somewhat heavier, since it may need an internal mutex of its own.

In C++20 it gained the only stop-aware waits in the library. `wait(lock, stoken, pred)` registers for the duration of the call to be woken when stop is requested on `stoken`, and then behaves as `while (!stoken.stop_requested()) { if (pred()) return true; wait(lock); } return pred();`. The result is the predicate's value, so a `false` return means "woken by a stop request, and the condition still does not hold". There are matching `wait_for` and `wait_until` overloads, all of which require a predicate.

```cpp
#include <condition_variable>
#include <mutex>
#include <queue>
#include <stop_token>
#include <thread>

std::mutex m;
std::condition_variable_any cv;
std::queue<int> jobs;

void worker(std::stop_token st) {
  while (true) {
    std::unique_lock lk(m);
    if (!cv.wait(lk, st, [] { return !jobs.empty(); }))
      return;                       // stop requested and no job is waiting
    jobs.pop();                     // ... process the job ...
  }
}

int main() {
  std::jthread t(worker);   // ~jthread requests stop, which wakes the wait
}
```

## Timed waits and clocks

`wait_until(lock, abs_time)` returns `std::cv_status::timeout` if the deadline has passed when it returns, and `no_timeout` otherwise, which includes spurious wakeups. `wait_for(lock, rel_time)` is specified as `wait_until(lock, std::chrono::steady_clock::now() + rel_time)`, so it measures elapsed time and is immune to someone changing the wall clock. A deadline expressed as a `system_clock` time point, by contrast, tracks adjustments to that clock. The clock types themselves belong to the chrono topic.

The predicate forms return `bool`, and on timeout they return the *predicate's value*, not `false`. A condition that became true just as the deadline expired is reported as success.

```cpp
#include <chrono>
#include <condition_variable>
#include <mutex>

std::mutex m;
std::condition_variable cv;
bool ready = false;

bool wait_ready() {
  std::unique_lock lk(m);
  // true if ready became true in time, or happened to be true at the deadline
  return cv.wait_for(lk, std::chrono::milliseconds(50), [] { return ready; });
}
```

[thread.req.timing] lets every timeout be late by an unspecified amount, for scheduling and resource reasons, so a timed wait is a lower bound on the delay, never an exact one.

## Lighter tools: atomic wait, semaphores, latches and barriers

C++20 added primitives that cover common patterns without a mutex.

`std::atomic<T>::wait(old)` blocks while the atomic's value equals `old`, and `notify_one` or `notify_all` wakes it. It is introduced in atomics-and-memory-ordering. Unlike a condition variable, it compares the value itself, so it returns at once if the value already differs and it never returns spuriously with the value unchanged. It can miss a change that is undone before it looks again, which is fine when you only wait for a value to move on.

`std::counting_semaphore<LeastMaxValue>` holds a counter. `acquire` blocks until the counter is positive and decrements it, `release(n)` adds `n`, and `try_acquire`, `try_acquire_for` and `try_acquire_until` are the non-blocking and timed forms; `try_acquire` is allowed to fail spuriously. A semaphore has no owner, so any thread may release it, which is exactly what a mutex forbids. `std::binary_semaphore` is `counting_semaphore<1>`. `max()` may be larger than the template argument, but releasing past `max()` is undefined behavior.

```cpp
#include <semaphore>

std::counting_semaphore<4> slots(4);   // at most four concurrent downloads

void download() {
  slots.acquire();
  // ... use one of the four slots ...
  slots.release();
}
```

`std::latch` is a single-use countdown. `count_down(n)` decrements, `wait` blocks until the count reaches zero, and `arrive_and_wait` does both. Decrementing below zero is undefined behavior, and a latch cannot be reset. Curiously, `try_wait` may return `false` "with very low probability" even after the count has reached zero.

`std::barrier<CompletionFunction>` is the reusable version, built around phases. Each participant calls `arrive_and_wait`; when the expected number have arrived, the completion function runs once on one of the arriving threads, and then everyone is released into the next phase. `arrive_and_drop` arrives and removes the caller from future phases. The completion function must be callable without throwing.

```cpp
#include <barrier>
#include <cstdio>
#include <thread>
#include <vector>

int main() {
  int phase = 0;
  std::barrier sync(3, [&]() noexcept { std::printf("phase %d done\n", ++phase); });
  std::vector<std::jthread> workers;
  for (int i = 0; i < 3; ++i)
    workers.emplace_back([&] {
      for (int step = 0; step < 2; ++step) {
        // ... this thread's share of the step ...
        sync.arrive_and_wait();   // nobody starts the next step until all finish
      }
    });
}   // prints "phase 1 done", then "phase 2 done"
```

> **Pitfall.** These primitives synchronize, but they do not protect data. A barrier orders the steps of different threads; it does not make two threads writing the same object inside one step race-free. Each still needs its own discipline: disjoint data or a mutex.

## Choosing a tool

- Waiting for arbitrary state guarded by a mutex: `condition_variable` with a predicate.
- The same, but with a non-`unique_lock` lock or with stop-token cancellation: `condition_variable_any`.
- Waiting for one atomic value to change: `atomic::wait` and `notify`.
- Limiting concurrency, or signalling between threads with no ownership: `counting_semaphore`.
- One-shot "everyone is ready" or "all work is done": `latch`.
- Repeated lock-step phases among a fixed group: `barrier`.
- Waiting for a single result, possibly an exception: a future, covered in futures-promises-and-async.

## What to remember

- Notifications are not remembered. A notify with no waiter does nothing.
- `wait` atomically unlocks and blocks, reacquires before returning, and may wake spuriously. Always use the predicate form.
- Change the predicate while holding the mutex, even if it is atomic; otherwise the wakeup can be lost.
- Notifying inside or outside the lock is correct; inside also protects a condition variable whose owner may destroy it on return.
- All concurrent waiters on one condition variable must use the same mutex.
- `condition_variable_any` takes any lockable and, since C++20, stop tokens; its stop-aware waits return the predicate's value.
- `wait_for` measures with `steady_clock`. Timed predicate waits return the predicate on timeout, and every timeout may be late.
- `atomic::wait` compares values and never returns spuriously with an unchanged value.
- Semaphores have no owner; latches are single-use; barriers repeat by phase and run a `noexcept` completion step.

## Concept Map Outline

- **Condition variables and waiting:** Sleep until mutex-guarded state changes, rechecking a predicate on every wake; C++20 adds lighter primitives.
  - **wait semantics:** Atomically unlock and block, then relock before returning.
    - **Spurious wakeups:** wait may return without any notify, so the predicate must be rechecked.
    - **Predicate overload:** wait(lock, pred) is while (!pred()) wait(lock); it returns at once if pred is true.
    - **unique_lock only:** condition_variable takes unique_lock<mutex>; a lock_guard cannot be unlocked by wait.
    - **One mutex:** All threads waiting at the same time must pass the same mutex, or behavior is undefined.
  - **Notification:** A notify is a nudge, never stored; with no waiter it does nothing.
    - **Lost wakeup:** Changing the predicate without the mutex lets a notify land between check and sleep.
    - **Atomic is not enough:** An atomic flag avoids a data race but not the lost wakeup; take the mutex to change it.
    - **Notify under lock:** Correct either way; under the lock also keeps a waiter from destroying the cv too early.
  - **condition_variable_any:** Works with any BasicLockable, such as shared_lock, at some extra cost.
    - **Stop-aware waits:** C++20 wait(lock, stoken, pred) wakes on stop requests and returns pred().
    - **False means stopped:** A false result means stop was requested while the predicate still did not hold.
  - **Timed waits:** wait_for and wait_until bound the sleep; timeouts may always be late.
    - **cv_status:** Bare timed waits return timeout or no_timeout; no_timeout includes spurious wakes.
    - **Predicate on timeout:** Predicate forms return the predicate's value at the deadline, not simply false.
    - **Clocks:** wait_for uses steady_clock; a system_clock deadline follows wall-clock adjustments.
  - **C++20 primitives:** Mutex-free tools for patterns a condition variable expresses clumsily.
    - **atomic::wait:** Blocks while the value equals old; returns at once if it differs; never spuriously unchanged.
    - **counting_semaphore:** acquire and release a counter; no owner, so any thread may release.
    - **latch:** Single-use countdown; going below zero is undefined; try_wait may rarely report false.
    - **barrier:** Reusable phases; a noexcept completion step runs once per phase on an arriving thread.
  - **Choosing:** Pick the narrowest primitive that expresses the wait.
    - **Arbitrary state:** Use a condition_variable with a predicate under the guarding mutex.
    - **One result:** Use a future when waiting for a single value or exception.

## Standardese Quiz Questions

### Question 1 [warmup] ([thread.condition.condvar])

What does this program do?

```cpp
#include <condition_variable>
#include <cstdio>
#include <mutex>

std::mutex m;
std::condition_variable cv;
bool ready = true;

int main() {
  std::unique_lock lk(m);
  cv.wait(lk, [] { return ready; });
  std::puts("done");
}
```

A. Blocks forever, because nothing ever calls `notify_one`
B. Prints `done` unless a spurious wakeup is missed
C. Undefined behavior: `wait` requires a matching notification
D. Prints `done`

**Answer (D):** Prints `done`

**Why:** `wait(lock, pred)` is specified as `while (!pred()) wait(lock);`, so the predicate is checked before the first sleep. It is already true, so `wait` returns at once without blocking. The first option is what the bare `wait(lock)` overload would do here, which is one more reason to always pass a predicate.

### Question 2 [warmup] ([thread.condition.condvar])

Is this code well-formed?

```cpp
#include <condition_variable>
#include <mutex>

std::mutex m;
std::condition_variable cv;
bool ready = false;

void waiter() {
  std::lock_guard<std::mutex> lk(m);
  cv.wait(lk, [] { return ready; });
}
```

A. Well-formed: any lock that holds `m` can be passed
B. Ill-formed: `std::condition_variable::wait` takes only `std::unique_lock<std::mutex>`
C. Well-formed, but undefined behavior because `lock_guard` cannot be unlocked
D. Ill-formed: the predicate must be a function pointer

**Answer (B):** Ill-formed: `std::condition_variable::wait` takes only `std::unique_lock<std::mutex>`

**Why:** Every `wait` overload of `std::condition_variable` takes a `std::unique_lock<std::mutex>&`, because the wait must unlock and relock it, and `lock_guard` offers neither operation. There is no conversion, so overload resolution fails and the code does not compile. `std::condition_variable_any` accepts any lockable type, but a `lock_guard` still lacks `lock` and `unlock`, so it would not work there either.

### Question 3 [warmup] ([thread.sema.cnt])

In C++20, what does this program print?

```cpp
#include <cstdio>
#include <semaphore>
#include <thread>

std::binary_semaphore sem(0);

int main() {
  std::thread t([] {
    std::puts("worker");
    sem.release();
  });
  sem.acquire();
  std::puts("main");
  t.join();
}
```

A. `worker` then `main`
B. `main` then `worker`, or the other way round
C. Undefined behavior: only the thread that acquired a semaphore may release it
D. Nothing: `acquire` blocks forever because the count starts at 0

**Answer (A):** `worker` then `main`

**Why:** The semaphore starts at 0, so `acquire` blocks until the worker's `release` makes it 1. A release strongly happens before an acquire that observes its effect, so the worker's `puts` comes first. Semaphores have no notion of ownership, unlike mutexes, so releasing from a different thread is the normal use, not undefined behavior.

### Question 4 [tricky] ([thread.condition.condvar], [thread.condition], [intro.races])

`waiter` and `setter` run concurrently in two threads, once each. Which statement is correct?

```cpp
#include <atomic>
#include <condition_variable>
#include <mutex>

std::mutex m;
std::condition_variable cv;
std::atomic<bool> ready{false};

void waiter() {
  std::unique_lock lk(m);
  cv.wait(lk, [] { return ready.load(); });
}

void setter() {
  ready = true;
  cv.notify_one();
}
```

A. Correct: the flag is atomic, so the waiter always wakes
B. Undefined behavior: data race on `ready`
C. No data race, but `waiter` can block forever
D. Correct, provided `notify_all` is used instead of `notify_one`

**Answer (C):** No data race, but `waiter` can block forever

**Why:** All accesses to `ready` are atomic, so there is no data race. But the setter does not take `m`, so it can store and notify after the waiter has checked the predicate and before it blocks; that notification finds no waiter and is lost, and the waiter then sleeps forever. Locking `m` around the store closes the window, because the waiter holds `m` from its check until the atomic unlock-and-block. `notify_all` loses the same race.

### Question 5 [tricky] ([atomics.wait], [atomics.types.operations])

In C++20, what does this program do?

```cpp
#include <atomic>
#include <cstdio>

int main() {
  std::atomic<int> a{1};
  a.wait(0);
  std::puts("returned");
}
```

A. Prints `returned`
B. Blocks forever, because nothing calls `notify_one`
C. Blocks until a spurious wakeup, then prints `returned`
D. Undefined behavior: `wait` needs a matching `notify`

**Answer (A):** Prints `returned`

**Why:** `a.wait(old)` blocks only while the value equals `old`: it loads, compares, and returns as soon as the values differ. The value is 1 and `old` is 0, so it returns at once. The tempting answer treats `wait` like a condition variable that sleeps until notified; the argument is the value you expect to change away from, not a value to wait for.

### Question 6 [tricky] ([thread.condition.condvar], [basic.life])

Which statement about `run` is correct?

```cpp
#include <condition_variable>
#include <mutex>
#include <thread>

void run() {
  std::mutex m;
  std::condition_variable cv;
  bool done = false;
  std::thread([&] {
    {
      std::lock_guard lk(m);
      done = true;
    }
    cv.notify_one();
  }).detach();
  std::unique_lock lk(m);
  cv.wait(lk, [&] { return done; });
}
```

A. It is correct: `done` is changed under the mutex, so nothing can go wrong
B. It can deadlock, because the notification may be lost
C. It is ill-formed: a detached thread cannot capture locals by reference
D. It can have undefined behavior: `run` may return and destroy `cv` before the worker calls `notify_one`

**Answer (D):** It can have undefined behavior: `run` may return and destroy `cv` before the worker calls `notify_one`

**Why:** The predicate is changed under the mutex, so no wakeup is lost; the waiter either sees `done` or is already blocked when the notification arrives. The problem is lifetime: after the worker unlocks, `run` may see `done`, for instance through a spurious wakeup or before ever blocking, return, and destroy `cv` while the worker is still about to call `notify_one` on it. Calling `notify_one` before the lock is released prevents this, because `run` cannot return from `wait` until it reacquires `m`.

### Question 7 [standardese] ([thread.condition.condvar])

Threads running `a` and `b` are both blocked on `cv` at the same time. What does the standard say?

```cpp
#include <atomic>
#include <condition_variable>
#include <mutex>

std::condition_variable cv;
std::mutex m1, m2;
std::atomic<bool> ready{false};

void a() {
  std::unique_lock lk(m1);
  cv.wait(lk, [] { return ready.load(); });
}

void b() {
  std::unique_lock lk(m2);
  cv.wait(lk, [] { return ready.load(); });
}
```

A. It is fine: each waiter reacquires its own mutex on wakeup
B. It is fine, but only `notify_all` is guaranteed to wake both
C. Undefined behavior: concurrent waiters must all use the same mutex
D. Ill-formed: a condition variable is bound to one mutex at construction

**Answer (C):** Undefined behavior: concurrent waiters must all use the same mutex

**Why:** A precondition of `std::condition_variable::wait` is that either no other thread is waiting on the object, or every concurrently waiting thread passed a lock on the same mutex. Two waiters with `m1` and `m2` violate it, so the behavior is undefined. Nothing binds the mutex at construction, which is why the code compiles; the constraint is on how waits overlap at run time. Using different mutexes at different, non-overlapping times is allowed.

### Question 8 [standardese] ([thread.condvarany.intwait])

In C++20, what does this program print?

```cpp
#include <condition_variable>
#include <cstdio>
#include <mutex>
#include <stop_token>

int main() {
  std::mutex m;
  std::condition_variable_any cv;
  std::stop_source src;
  src.request_stop();
  std::unique_lock lk(m);
  bool r = cv.wait(lk, src.get_token(), [] { return false; });
  std::printf("%d\n", r);
}
```

A. `1`, because the wait ended without a timeout
B. `0`
C. Nothing: it blocks forever, because nobody notifies `cv`
D. Nothing: a stop request makes the wait throw

**Answer (B):** `0`

**Why:** The stop-aware `wait` is specified as `while (!stoken.stop_requested()) { if (pred()) return true; wait(lock); } return pred();`. Stop was already requested, so the loop body never runs and the function returns `pred()`, which is `false`. The result always reports the predicate, so a `false` return means stop was requested while the condition still did not hold. Nothing is thrown, and no notification is needed.
