std::condition_variable的简单demo
时间: 2024-01-04 09:19:32 浏览: 33
以下是一个使用std::condition_variable的简单示例代码:
```cpp
#include <iostream>
#include <thread>
#include <condition_variable>
std::mutex mtx;
std::condition_variable cv;
bool ready = false;
void worker_thread()
{
// 模拟一些工作
std::this_thread::sleep_for(std::chrono::seconds(2));
// 工作完成后通知主线程
{
std::lock_guard<std::mutex> lock(mtx);
ready = true;
}
cv.notify_one();
}
int main()
{
std::thread worker(worker_thread);
// 等待工作完成
{
std::unique_lock<std::mutex> lock(mtx);
cv.wait(lock, []{ return ready; });
}
std::cout << "工作已完成!" << std::endl;
worker.join();
return 0;
}
```
相关问题
std::condition_variable wait
std::condition_variable的wait函数用于等待一个条件达成。它需要与std::unique_lock<std::mutex>一起使用,以确保在等待期间互斥量被正确地锁定和解锁。
以下是一个示例代码,演示了如何使用std::condition_variable的wait函数等待条件达成:
```cpp
#include <iostream>
#include <thread>
#include <condition_variable>
std::mutex mtx;
std::condition_variable cv;
bool condition = false;
void worker()
{
std::unique_lock<std::mutex> lock(mtx);
cv.wait(lock, []{ return condition; }); // 等待条件达成
// 条件达成后的操作
std::cout << "条件已达成,执行操作" << std::endl;
}
int main()
{
std::thread t(worker);
// 模拟条件达成
std::this_thread::sleep_for(std::chrono::seconds(2));
{
std::lock_guard<std::mutex> lock(mtx);
condition = true;
}
cv.notify_one(); // 通知等待的线程条件已达成
t.join();
return 0;
}
```
在上述示例中,worker函数是一个工作线程,它在等待条件达成之前会一直阻塞。在主线程中,通过改变condition的值,并调用cv.notify_one()来通知工作线程条件已达成。一旦条件达成,工作线程会被唤醒并执行相应的操作。
std::condition_variable头文件是啥
std::condition_variable是C++标准库中的一个头文件,它提供了一种线程间同步的机制,于等待和通知线程。它通常与std::mutex(互斥锁)一起使用,用于实现线程间的条件等待和唤醒。
std::condition_variable的主要作用是在某个条件满足时,使一个或多个线程等待,直到其他线程通知它们继续执行。它提供了以下几个重要的成员函数:
1. wait():使当前线程等待,直到其他线程调用notify_one()或notify_all()来唤醒它。
2. notify_one():唤醒一个等待在condition_variable上的线程。
3. notify_all():唤醒所有等待在condition_variable上的线程。
使用std::condition_variable时,通常需要结合std::unique_lock<std::mutex>来进行加锁和解锁操作。当某个线程调用wait()时,它会自动释放锁,并进入等待状态,直到其他线程通知它继续执行。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)