wiki:hpp-condition-variable
Table of Contents
<condition_variable>
<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.
// 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; }
wiki/hpp-condition-variable.md · Last modified: by 127.0.0.1
