std::condition_variable
时间: 2023-09-01 19:10:27 浏览: 116
std::condition_variable is a synchronization primitive provided by the C++ Standard Library that enables threads to wait for a certain condition to become true. It is typically used in conjunction with a std::mutex to protect access to shared data.
The basic idea is that one or more threads wait on the condition variable until some other thread signals it. The waiting threads are blocked until the condition variable is notified, at which point one or more of them are unblocked and can proceed.
To use std::condition_variable, you typically follow these steps:
1. Define a std::condition_variable object.
2. Define a std::mutex object to protect access to shared data.
3. Define a boolean variable that represents the condition that the threads are waiting for.
4. Use the mutex to protect access to the shared data and the condition variable.
5. When a thread needs to wait for the condition to become true, it calls wait() on the condition variable while holding the mutex.
6. When the condition becomes true, some other thread calls notify_one() or notify_all() on the condition variable to wake up the waiting thread(s).
Here's some example code:
```
#include <mutex>
#include <condition_variable>
#include <thread>
#include <iostream>
std::mutex mtx;
std::condition_variable cv;
bool ready = false;
void worker()
{
std::unique_lock<std::mutex> lock(mtx);
while (!ready) {
cv.wait(lock);
}
std::cout << "Worker thread got signal!\n";
}
int main()
{
std::thread t(worker);
// Do some work here...
{
std::lock_guard<std::mutex> lock(mtx);
ready = true;
}
cv.notify_one();
t.join();
return 0;
}
```
In this example, the main thread starts a worker thread and does some work. When the work is done, it signals the worker thread by setting the "ready" flag to true and calling notify_one() on the condition variable. The worker thread is blocked on the condition variable until it receives the signal, at which point it prints out a message.
阅读全文