September 12, 2026

std::condition_variable Is Not an Event

A std::condition_variable does not remember that you called notify_one(). If your synchronization depends on remembering that notification, the design is probably wrong.

This is one of the easiest mistakes to make when condition variables are treated like events, signals or messages.

One thread finishes some work and calls:

cv.notify_one();

Another thread waits:

std::unique_lock lock(mutex);
cv.wait(lock);

It looks like a producer sends an event and a consumer receives it.

That is the wrong mental model.

The notification carries no durable information. It does not contain the work item. It does not mean that a queue is non-empty. It does not mean that initialization completed. It does not remember that shutdown was requested. It only gives waiting threads a reason to check shared state again.

The rule worth remembering

The predicate is the state. The notification is only a hint that the state may have changed.

1 condition variableisnotanevent

The broken mental model: notify means an event happened


Consider this simplified worker:

std::mutex mutex;
std::condition_variable cv;

void worker()
{
    std::unique_lock lock(mutex);

    cv.wait(lock);

    processWork();
}

void submitWork()
{
    cv.notify_one();
}

The intended contract seems obvious: submitWork() wakes worker().

But what happens if the order is this?

// Thread A
submitWork();      // notify_one()

// ...later...

// Thread B
worker();          // starts waiting

The notification is already gone.

The condition variable does not keep a pending notification for a future waiter. Thread B can block indefinitely because there is no state telling it that work already exists.

This is often described as a lost wakeup, but the more useful diagnosis is that the design has no persistent state.

Common mistake

If correctness depends on whether notify_one() happened before or after another thread entered wait(), the protocol is probably incomplete.

2 condition variableisnotanevent

The condition must exist independently of the notification


The correct design introduces state representing what the consumer actually cares about.

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

void worker()
{
    std::unique_lock lock(mutex);

    cv.wait(lock, [] {
        return ready;
    });

    processWork();
}

void submitWork()
{
    {
        std::lock_guard lock(mutex);
        ready = true;
    }

    cv.notify_one();
}

Now the protocol no longer depends on remembering the notification.

If submitWork() executes first, ready remains true. When the worker later calls the predicate overload of wait(), the predicate succeeds immediately and the thread does not block.

If the worker arrives first, it observes ready == false, releases the mutex as part of entering the wait and blocks. The producer later changes the state and notifies it.

The important part is that the notification is no longer responsible for carrying meaning. ready carries the meaning.

Mental model

A condition variable lets a thread sleep efficiently while some predicate over shared state is false. When it wakes, it checks that predicate again.

wait(lock, predicate) is the form you usually want


The predicate overload:

cv.wait(lock, [] {
    return ready;
});

has the same basic logic as:

while (!ready) {
    cv.wait(lock);
}

That loop is not defensive boilerplate. It is the condition-variable protocol.

The thread asks:

  • Is the state I need already available?
  • If not, sleep.
  • After waking, check the state again.
  • Continue only when the predicate is actually true.

This also handles spurious wakeups. A waiting thread is allowed to wake even when no useful state transition occurred. If the code assumes every wake means useful work exists, the program can continue with invalid assumptions.

// Wrong.
cv.wait(lock);

auto job = std::move(queue.front()); // queue may still be empty
queue.pop();

The predicate makes the actual requirement explicit:

cv.wait(lock, [this] {
    return !queue.empty();
});

auto job = std::move(queue.front());
queue.pop();

Do not translate wakeup into truth

“The thread woke up” and “the condition I need is true” are two different statements. Always make the second one explicit.

3 condition variableisnotanevent

The mutex connects the state check with going to sleep


There is another important part of the protocol: the predicate and its state are normally protected by the same mutex used by the condition variable wait.

Without that relationship, this race becomes possible:

  1. The consumer checks the state and sees “not ready”.
  2. The producer changes the state and calls notify_one().
  3. The consumer has not actually started waiting yet.
  4. The consumer enters the wait after the notification.
  5. No later notification arrives, so it sleeps even though the state is ready.

condition_variable::wait() avoids this gap by coordinating the mutex unlock with entering the wait.

The usual protocol is therefore:

// Consumer
std::unique_lock lock(mutex);

cv.wait(lock, [&] {
    return predicate();
});

// predicate is true and mutex is locked again

and:

// Producer
{
    std::lock_guard lock(mutex);
    changeSharedState();
}

cv.notify_one();

The producer cannot modify the protected predicate state in the dangerous interval between the consumer checking it and the consumer becoming waitable, because the consumer owns the mutex during that transition.

When the consumer wakes, wait() reacquires the mutex before returning. The code after the wait therefore observes the synchronized shared state while still owning the lock.

4 condition variableisnotanevent

An atomic flag does not automatically fix the protocol


A common attempted fix is to make the state atomic:

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

void worker()
{
    if (!ready.load()) {
        std::unique_lock lock(mutex);
        cv.wait(lock);
    }

    processWork();
}

The data race on ready may be gone. The synchronization protocol is still broken.

The producer can set ready = true and notify after the load but before the consumer has entered the wait.

The consumer then waits for a notification that already happened.

Race-free does not mean protocol-correct

An atomic can remove a data race while leaving a lost-wakeup race intact. The state check and the transition into waiting still need a correct synchronization relationship.

If the synchronization really consists of one atomic value, C++20’s std::atomic::wait() and notify_one()/notify_all() may provide a simpler model. But the same principle remains: the atomic value is the state. The notification is not.

A realistic worker queue


A worker queue is a more useful production example because the condition is not a boolean event. The condition is derived from actual application state:

!queue_.empty()

A basic implementation can look like this:

class WorkQueue
{
public:
    void push(Job job)
    {
        {
            std::lock_guard lock(mutex_);
            queue_.push(std::move(job));
        }

        notEmpty_.notify_one();
    }

    bool waitAndPop(Job& job)
    {
        std::unique_lock lock(mutex_);

        notEmpty_.wait(lock, [this] {
            return stopping_ || !queue_.empty();
        });

        if (queue_.empty()) {
            return false;
        }

        job = std::move(queue_.front());
        queue_.pop();

        return true;
    }

    void stop()
    {
        {
            std::lock_guard lock(mutex_);
            stopping_ = true;
        }

        notEmpty_.notify_all();
    }

private:
    std::mutex mutex_;
    std::condition_variable notEmpty_;

    std::queue<Job> queue_;
    bool stopping_{false};
};

There are two pieces of persistent state:

  • queue_.empty() tells workers whether work exists;
  • stopping_ tells them whether waiting should end.

The condition variable itself represents neither of these things.

This is important during shutdown. If four worker threads are sleeping and the process wants all of them to exit, setting stopping_ = true records the shutdown state. notify_all() merely gives every blocked worker an opportunity to observe that state.

If one worker starts its next iteration after the notification has already happened, it still sees stopping_ == true and does not block again.

Production pattern

For shutdown, record shutdown in shared state first. Then wake the waiters. Never make “the stop notification happened” the only representation of shutdown.

5 condition variableisnotanevent

Shutdown semantics need to be designed, not improvised


The queue example also exposes a real design decision: what should happen to already queued work when shutdown starts?

The implementation above drains existing jobs before workers exit. After stopping_ becomes true, a worker still removes a queued job when one exists. It returns false only once the queue is empty.

Another product may need immediate cancellation:

notEmpty_.wait(lock, [this] {
    return stopping_ || !queue_.empty();
});

if (stopping_) {
    return false;
}

Now queued work is abandoned after shutdown begins.

Both designs can be correct. They express different lifecycle contracts.

This is why the predicate deserves design attention. A predicate such as:

stopping_ || !queue_.empty()

is not merely syntax required by condition_variable. It describes when the worker is allowed to make progress.

notify_one and notify_all are scheduling choices, not state changes


Once the state model is correct, choosing between notify_one() and notify_all() becomes easier.

When one new queue item arrives, waking one worker is often enough:

{
    std::lock_guard lock(mutex_);
    queue_.push(std::move(job));
}

notEmpty_.notify_one();

When shutdown changes a condition that applies to every worker, waking all waiters usually matches the state transition:

{
    std::lock_guard lock(mutex_);
    stopping_ = true;
}

notEmpty_.notify_all();

Do not interpret this as “one notification represents one job”. It does not.

Suppose ten jobs are inserted while several workers are asleep, but only one notification is sent. One worker may wake and process the queue while the others remain asleep. Correctness may still be preserved because the queue state persists, but parallelism may be poor.

That distinction matters in production:

  • The predicate determines correctness.
  • The notification strategy influences latency, contention and parallelism.

Do not count notifications

Condition-variable notifications can be coalesced from the application’s point of view. If you need a synchronization primitive that remembers a number of available permits, a counting semaphore is usually a better model.

Update the state first, then notify


Another common mistake is sending the notification before changing the predicate state:

// Wrong protocol.
cv.notify_one();

{
    std::lock_guard lock(mutex);
    ready = true;
}

A waiter can wake, reacquire the mutex, observe ready == false and correctly return to sleep. The producer then changes ready but sends no second notification.

The state should become true before the notification:

{
    std::lock_guard lock(mutex);
    ready = true;
}

cv.notify_one();

This ordering communicates the intended protocol clearly: first make progress possible, then wake someone who may be able to make that progress.

Should notify_one be called while holding the mutex?


You will see both styles:

{
    std::lock_guard lock(mutex);
    ready = true;
    cv.notify_one();
}

and:

{
    std::lock_guard lock(mutex);
    ready = true;
}

cv.notify_one();

Both can be correct when the predicate state is properly protected.

Notifying after unlocking is common because a woken thread can immediately compete for the mutex instead of necessarily waking while the producer still owns it.

But this is primarily a contention and protocol-lifetime decision, not the fundamental correctness rule.

What actually matters

Protect the predicate state correctly and make the state change before the notification. Whether notification itself happens just before or just after unlocking is a secondary design decision.

Multiple conditions often deserve multiple condition variables


A bounded queue often has two independent conditions:

  • consumers wait for the queue to become not empty;
  • producers wait for the queue to become not full.

You can put both groups on one condition variable because each waiter rechecks its own predicate. But this can wake the wrong category of waiter and create unnecessary scheduling traffic.

A clearer design often uses two condition variables:

class BoundedQueue
{
public:
    explicit BoundedQueue(std::size_t capacity)
        : capacity_(capacity)
    {
    }

    void push(Job job)
    {
        std::unique_lock lock(mutex_);

        notFull_.wait(lock, [this] {
            return stopping_ || queue_.size() < capacity_;
        });

        if (stopping_) {
            return;
        }

        queue_.push(std::move(job));

        lock.unlock();
        notEmpty_.notify_one();
    }

    bool pop(Job& job)
    {
        std::unique_lock lock(mutex_);

        notEmpty_.wait(lock, [this] {
            return stopping_ || !queue_.empty();
        });

        if (queue_.empty()) {
            return false;
        }

        job = std::move(queue_.front());
        queue_.pop();

        lock.unlock();
        notFull_.notify_one();

        return true;
    }

private:
    const std::size_t capacity_;

    std::mutex mutex_;
    std::condition_variable notEmpty_;
    std::condition_variable notFull_;

    std::queue<Job> queue_;
    bool stopping_{false};
};

The names now document the protocol. Consumers wait on notEmpty_. Producers wait on notFull_.

Again, the variables themselves do not store “not empty” or “not full”. Those conditions come from queue_ and capacity_.

6 condition variableisnotanevent

Timed waits have their own trap


Timeout logic becomes subtle when code manually repeats a relative wait after every wakeup.

Consider:

while (!ready) {
    if (cv.wait_for(lock, 5s) == std::cv_status::timeout) {
        return false;
    }
}

If the thread repeatedly wakes before the timeout and re-enters wait_for(), each iteration starts another five-second relative wait. The total operation can therefore take much longer than the intended deadline.

Use the predicate overload when it matches the API:

if (!cv.wait_for(lock, 5s, [&] {
        return ready;
    })) {
    return false;
}

Or compute an absolute deadline once:

const auto deadline =
    std::chrono::steady_clock::now() + 5s;

while (!ready) {
    if (cv.wait_until(lock, deadline) ==
        std::cv_status::timeout) {
        return ready;
    }
}

std::chrono::steady_clock is normally the right clock for measuring a timeout because it is monotonic and does not jump when the wall clock is corrected.

Timeout rule

If the requirement is “finish by this deadline”, represent a deadline. Do not accidentally restart the full timeout after every unrelated wakeup.

When a semaphore is the better abstraction


Sometimes developers are trying to make a condition variable behave like a primitive that really does remember signals.

For example:

signal();
signal();
signal();

// Later:
wait();
wait();
wait();

If the intended meaning is “three units of work or three permits became available”, a counting semaphore models that directly.

#include <semaphore>

std::counting_semaphore<> available{0};

void produce()
{
    createWorkItem();
    available.release();
}

void consume()
{
    available.acquire();
    processWorkItem();
}

release() increments the semaphore’s permit count. If no thread is currently waiting, that permit still exists for a future acquire().

That is fundamentally different from condition_variable::notify_one().

PrimitiveWhat carries the state?Does a signal persist for a future waiter?Typical use
std::condition_variableYour shared predicate stateNoWait until complex shared state satisfies a condition
std::counting_semaphoreInternal permit countYesResource permits, work counts, bounded concurrency
std::atomic::waitThe atomic valueThe value persists, not the notificationWaiting on one simple atomic state
std::latchInternal countdownCompletion remains observableOne-shot phase completion
std::barrierPhase participation stateManaged by the barrierRepeated synchronization phases

Choosing the right primitive often removes synchronization complexity rather than hiding it behind another wrapper.

7 condition variableisnotanevent

Common production failure modes


Most condition-variable bugs I would look for during code review fall into a small number of patterns.

Failure modeWhat goes wrongBetter design
Bare wait(lock)Code assumes every wake means useful state existsWait with an explicit predicate
Notification is the only “state”A notification before the waiter exists is lostStore the real condition separately
Predicate checked outside the mutexState can change between check and entering waitCoordinate predicate check and waiting with the same mutex
State updated after notificationWaiter wakes, sees old state and sleeps againChange state first, then notify
Shutdown only calls notify_all()Late or spuriously waking threads cannot tell that shutdown was requestedStore a shutdown flag or lifecycle state
Relative timeout restarted in a loopRepeated wakes extend total waiting timeUse predicate overload or one absolute deadline
One condition variable for unrelated predicatesWrong categories of waiters wake frequentlyConsider separate condition variables
Object destroyed while waiters still use itCondition variable, mutex or predicate state lifetime ends too earlyJoin/stop workers before destroying synchronization state

Debug the state transitions, not only the notifications


Condition-variable bugs are frustrating because adding logging often changes thread scheduling enough to hide them.

The first useful rule during debugging is to instrument the state that controls the predicate.

This log is weak:

logDebug("calling notify_one");

This is much more useful:

logDebug("queue push: depth={}, stopping={}",
         queue_.size(),
         stopping_);

And on the waiting side, record why a thread actually progressed:

notEmpty_.wait(lock, [this] {
    return stopping_ || !queue_.empty();
});

logDebug("worker resumed: depth={}, stopping={}",
         queue_.size(),
         stopping_);

You are trying to reconstruct the state machine, not count calls to notify_one().

Use ThreadSanitizer for data races

With GCC or Clang, ThreadSanitizer can find many unsynchronized accesses that otherwise appear only under unlucky timing:

-fsanitize=thread -fno-omit-frame-pointer -g

ThreadSanitizer will not prove that your higher-level condition-variable protocol is correct. A program can be data-race-free and still have a lost wakeup or deadlock. But it is a good first filter because predicate state accessed without the intended mutex often appears as a race.

Inspect blocked threads

When a process is hung, attach a debugger and inspect all thread stacks:

gdb -p <pid>

Then:

thread apply all bt

If every worker is blocked in condition-variable waiting while your queue metrics show pending work, the next question is not “why didn’t pthread wake them?” Start by checking which state transition inserted the work and which notification strategy followed it.

On Linux, futex traces can provide another clue

Many Linux C++ standard-library implementations eventually use futex-based primitives underneath condition variables. When diagnosing a difficult target, tracing futex activity can sometimes show whether threads are repeatedly blocking and waking:

strace -f -e futex ./application

This is implementation-level evidence, not the condition-variable contract itself. Do not try to reconstruct application correctness by counting futex wake calls. Use it to complement your state-level diagnostics.

Stress the transition boundaries

Concurrency tests should repeatedly exercise the uncomfortable boundaries:

  • producer runs before consumer starts waiting;
  • consumer enters the wait just as work arrives;
  • many producers wake a small worker pool;
  • shutdown happens with an empty queue;
  • shutdown happens with queued work;
  • worker wakes repeatedly without its own predicate becoming true;
  • timeout races with the state becoming ready.

A test that sleeps for 100 ms and assumes the other thread reached a particular line is usually testing the scheduler more than your synchronization design. Prefer explicit barriers, latches or test hooks when you need to force a particular interleaving.

8 condition variableisnotanevent

Do not let the synchronization object’s lifetime race with the workers


One failure mode is not about wakeup semantics at all. It is object lifetime.

If an object owns:

  • the condition variable;
  • the mutex;
  • the predicate state;
  • and the worker threads using them;

its destruction sequence must guarantee that workers have stopped using all of those members before the members are destroyed.

A typical shutdown sequence is:

  1. Set the persistent stop state under the mutex.
  2. Call notify_all().
  3. Join all worker threads.
  4. Only then destroy the mutex, condition variable and shared state.

Do not rely on a destructor calling notify_all() and immediately allowing synchronization objects to disappear while workers are still unwinding from their waits.

Lifetime rule

Waking a thread does not mean the thread has finished using the object. Shutdown is complete only when ownership and thread lifetime say it is complete.

A useful way to review condition-variable code


When reviewing production C++ that uses std::condition_variable, I would ask these questions in order:

  1. What persistent state represents the condition? Queue depth, lifecycle state, generation counter, available resource, completed operation?
  2. What exact predicate allows this thread to proceed? It should be possible to write it down clearly.
  3. Which mutex protects that predicate? The state check and the wait protocol need to agree on synchronization.
  4. Who changes the predicate state? Verify that those transitions happen under the intended synchronization.
  5. Does the state change happen before notification?
  6. Does every waiter re-check its predicate after waking?
  7. Should this transition wake one waiter or all relevant waiters?
  8. What happens during shutdown? Late waiters must still observe the stopped state.
  9. What happens on timeout? Make sure repeated wakeups cannot accidentally extend a fixed deadline.
  10. Who owns the waiting threads and synchronization state? Destruction must happen after the workers stop using them.

If the answers require talking about how many times notify_one() was called rather than what shared state currently says, that is a warning sign.

The production rule is simple


std::condition_variable is easiest to reason about when you stop treating it as an event channel.

The queue remembers that jobs exist.

The state machine remembers that shutdown started.

The boolean remembers that initialization completed.

The generation counter remembers that configuration changed.

The condition variable remembers none of these things.

It only lets a thread sleep while its predicate is false and wake efficiently when another thread believes that predicate may have changed.

Final rule

If removing the notification from your explanation makes you unable to describe what state the program is waiting for, start with the state model again. The predicate is the contract. notify_one() is only part of how you schedule another check.

9 condition variableisnotanevent