condition_variable使用方法
时间: 2024-06-13 20:06:31 浏览: 178
condition_variable是C++11中的一个同步原语,常和mutex搭配使用,用于阻塞一个线程或同时阻止多个线程,直到另一个线程修改共享变量并通知condition_variable。它可以防止多线程场景下,共享变量混乱。理解条件变量需要先理解三个概念:锁、wait等待和notify通知。
condition_variable的使用方法如下:
1.定义condition_variable对象和mutex对象
```c++
std::condition_variable cv;
std::mutex cv_m;
```
2.资源修改线程步骤
```c++
std::unique_lock<std::mutex> lk(cv_m);
// 修改共享变量
cv.notify_one(); // 通知等待的线程
```
3.资源等待线程步骤
```c++
std::unique_lock<std::mutex> lk(cv_m);
cv.wait(lk, []{return true/false;}); // 等待条件变量
```
其中,wait函数会自动释放锁,等待条件变量被通知后重新获取锁。
4.代码示例
4.1 无需notify场景
```c++
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
std::mutex mtx;
std::condition_variable cv;
bool ready = false;
void print_id(int id) {
std::unique_lock<std::mutex> lck(mtx);
while (!ready) cv.wait(lck);
std::cout << "thread " << id << '\n';
}
void go() {
std::unique_lock<std::mutex> lck(mtx);
ready = true;
cv.notify_all();
}
int main() {
std::thread threads[10];
for (int i = 0; i < 10; ++i)
threads[i] = std::thread(print_id, i);
std::cout << "10 threads ready to race...\n";
go();
for (auto& th : threads) th.join();
return 0;
}
```
4.2 正常应用场景1
```c++
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
std::mutex mtx;
std::condition_variable cv;
bool data_ready = false;
void consumer() {
std::unique_lock<std::mutex> lck(mtx);
cv.wait(lck, []{return data_ready;});
std::cout << "Consumer: data is ready\n";
}
void producer() {
std::unique_lock<std::mutex> lck(mtx);
data_ready = true;
cv.notify_one();
}
int main() {
std::thread t1(consumer);
std::thread t2(producer);
t1.join();
t2.join();
return 0;
}
```
4.3 正常应用场景2
```c++
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
std::mutex mtx;
std::condition_variable cv;
bool data_ready = false;
void consumer() {
std::unique_lock<std::mutex> lck(mtx);
cv.wait(lck, []{return data_ready;});
std::cout << "Consumer: data is ready\n";
data_ready = false;
}
void producer() {
std::unique_lock<std::mutex> lck(mtx);
data_ready = true;
cv.notify_one();
}
int main() {
std::thread t1(consumer);
std::thread t2(producer);
t1.join();
t2.join();
return 0;
}
```
阅读全文