Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::condition_variable: waiting for shared state to change

std::condition_variable blocks a thread while atomically unlocking a mutex and wakes it after notification, but the condition must always be checked again.

Version: C++23

Syntax

class condition_variable {
public:
    void notify_one() noexcept;
    void notify_all() noexcept;
    void wait(std::unique_lock<std::mutex>& lock);
    template<class Predicate>
    void wait(std::unique_lock<std::mutex>& lock, Predicate pred);
};

std::condition_variable from <condition_variable> coordinates threads using std::unique_lock<std::mutex>. wait atomically unlocks the mutex and blocks, then reacquires the lock before returning. notify_one wakes one waiting thread, while notify_all wakes all of them.

A notification stores no state and can be lost when nobody is waiting yet. Modify state such as ready under the same mutex and wait with wait(lock, pred), which repeats the check after spurious wakeups. Notification can be issued after unlocking to reduce contention.

The supplied unique_lock must own its lock, and all threads waiting on the same object must use the same mutex; violating these requirements causes undefined behavior. A timed wait can return later than its deadline. Destroy the condition variable once no thread remains blocked on it; an unblocked thread may still be waiting to reacquire the mutex. Joining all threads, as the example does, is a safe lifetime pattern rather than the standard’s literal requirement.

Examples

#include <condition_variable>
#include <iostream>
#include <mutex>
#include <thread>

int main() {
    std::mutex mutex;
    std::condition_variable ready_changed;
    bool ready = false;
    int value = 0;

    std::jthread worker([&] {
        std::unique_lock lock(mutex);
        ready_changed.wait(lock, [&] { return ready; });
        value *= 2;
    });

    {
        std::lock_guard lock(mutex);
        value = 21;
        ready = true;
    }
    ready_changed.notify_one();
    worker.join();
    std::cout << value << '\n';
}

Result

42

std::condition_variable → 42

Sources