# **[](https://en.cppreference.com/w/cpp/header/condition_variable)** provides `std::condition_variable` for efficient thread coordination: one or more threads wait on a condition, and others signal when it changes. It pairs with a `std::mutex` to avoid race conditions around the condition check. This is the go-to tool for producer-consumer queues, thread-safe event systems, and any scenario where a thread should sleep until a specific event occurs. ## Example This example implements a producer-consumer pattern where a producer thread pushes values and a consumer thread waits for and processes them. ```cpp // compile: g++ -std=c++11 -pthread -o condvarexample condvarexample.cpp // run: ./condvarexample // description: producer and consumer with condition_variable #include #include #include #include #include std::queue data; std::mutex mtx; std::condition_variable cv; void producer() { for (int i = 0; i < 3; ++i) { { std::lock_guard lock(mtx); data.push(i); } cv.notify_one(); } } void consumer() { for (int i = 0; i < 3; ++i) { std::unique_lock lock(mtx); cv.wait(lock, [] { return !data.empty(); }); int val = data.front(); data.pop(); std::cout << "consumed: " << val << "\n"; } } int main() { std::thread p(producer); std::thread c(consumer); p.join(); c.join(); return 0; } ```