skip to content
Ivan's wiki
Site Tools
Search
Tools
Show pagesource
Backlinks
Recent Changes
Media Manager
Sitemap
>
Recent Changes
Media Manager
Sitemap
hpp-condition-variable
This page is read only. You can view the source, but not change it.
# <condition_variable> **[<condition_variable>](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. 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 <condition_variable> #include <iostream> #include <mutex> #include <thread> #include <queue> std::queue<int> data; std::mutex mtx; std::condition_variable cv; void producer() { for (int i = 0; i < 3; ++i) { { std::lock_guard<std::mutex> lock(mtx); data.push(i); } cv.notify_one(); } } void consumer() { for (int i = 0; i < 3; ++i) { std::unique_lock<std::mutex> 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; } ```
Page Tools
Show pagesource
Backlinks
Back to top