Skip to content
Tutorials Center
My learning

Topics

C++ Reference ยท Concurrency

C++ std::condition_variable class

Reference for std::condition_variable and condition_variable_any: wait with a predicate, notify_one, notify_all, wait_for, spurious wakeups and lost-wakeup bugs.

std::condition_variable (header <condition_variable>) lets a thread sleep until another thread signals that something it cares about may have changed. It is always used together with a mutex and a shared condition (a flag, a queue that is not empty, a counter that reached zero). The mutex protects the condition; the condition variable only provides the sleeping and waking.

The pattern has two sides. The waiter locks the mutex and calls wait(lock, predicate), which unlocks the mutex while sleeping and relocks it before returning. The notifier changes the condition while holding the mutex, then calls notify_one() or notify_all().

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

// waiter
std::unique_lock lock(m);
cv.wait(lock, [] { return ready; });    // sleeps until ready is true

// notifier
{ std::lock_guard g(m); ready = true; }
cv.notify_one();

Try it

C++ A producer and a consumer with a queue

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

C++ wait_for with a timeout

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Syntax

C++
class condition_variable {
public:
    void notify_one() noexcept;
    void notify_all() noexcept;

    void wait(std::unique_lock<std::mutex>& lock);
    template<class Pred> void wait(std::unique_lock<std::mutex>& lock, Pred pred);

    template<class Rep, class Period>
    std::cv_status wait_for(std::unique_lock<std::mutex>& lock,
                            const std::chrono::duration<Rep, Period>& rel_time);
    template<class Rep, class Period, class Pred>
    bool wait_for(std::unique_lock<std::mutex>& lock,
                  const std::chrono::duration<Rep, Period>& rel_time, Pred pred);

    // wait_until(lock, time_point [, pred]) works the same with an absolute time
};
Name Description
lock A std::unique_lock<std::mutex> that the calling thread has locked. It is unlocked during the wait and locked again before wait returns.
pred A callable returning bool. wait(lock, pred) is equivalent to while (!pred()) wait(lock);.
rel_time How long to wait at most.

Returns: wait returns nothing. wait_for and wait_until without a predicate return std::cv_status::timeout or no_timeout; with a predicate they return the final value of pred().

Errors / undefined behavior: calling wait without owning lock, or with a lock on a different mutex than other concurrent waiters use, is undefined. Destroying a condition variable while threads still wait on it is undefined.

Usage notes

  • Always wait with a predicate. Waking up does not guarantee the condition is true: spurious wakeups are allowed, and another thread may consume the item first.
  • Lost wakeup: if you set the flag without holding the mutex, the waiter can check the predicate, then you set the flag and notify, then the waiter goes to sleep and never wakes. Change the condition under the mutex.
  • Notify after or before unlocking? Both are correct. Notifying after releasing the mutex avoids waking a thread that immediately blocks on the mutex.
  • notify_one vs notify_all: use notify_all when several waiters may be able to proceed or wait for different conditions (for example shutdown); otherwise notify_one.
  • Only std::unique_lock<std::mutex> works with condition_variable. std::condition_variable_any works with any lock type and std::stop_token (C++20) at some extra cost.
  • A notification with no waiter is lost. The state must live in your variable, not in the signal.
  • Shutdown: include a done flag in the predicate, as in the first example, so consumers can exit cleanly.
  • Do not use it for tight polling. If the wait is short, an atomic or a latch may be simpler.