C++笔记之条件变量(Condition Variable)与cv.wait 和 cv.wait_for的使用
参考博客:C++笔记之各种sleep方法总结
code review!
文章目录
- C++笔记之条件变量(Condition Variable)与cv.wait 和 cv.wait_for的使用
- 1.条件变量(Condition Variable)
- 2.cv.wait_for
- 3.cv.wait
- 4.cv.wait和cv.wait_for比较
1.条件变量(Condition Variable)
2.cv.wait_for
代码
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
std::mutex mtx;
std::condition_variable cv;
bool condition = false;
void waitForCondition() {
std::unique_lock<std::mutex> lock(mtx);
// 等待一段时间,或直到条件满足
if (cv.wait_for(lock, std::chrono::seconds(3), []{ return condition; })) {
std::cout << "Condition is satisfied!" << std::endl;
} else {
std::cout << "Timed out waiting for condition." << std::endl;
}
}
void notifyCondition() {
std::this_thread::sleep_for(std::chrono::seconds(2)); // 模拟一些操作
{
std::lock_guard<std::mutex> lock(mtx);
condition = true;
}
cv.notify_one(); // 通知一个等待的线程
}
int main() {
std::thread t1(waitForCondition);
std::thread t2(notifyCondition);
t1.join();
t2.join();
return 0;
}
3.cv.wait
代码
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
std::mutex mtx;
std::condition_variable cv;
bool condition = false;
void waitForCondition() {
std::unique_lock<std::mutex> lock(mtx);
cv.wait(lock, []{ return condition; }); // 等待条件满足
std::cout << "Condition is satisfied!" << std::endl;
}
void notifyCondition() {
std::this_thread::sleep_for(std::chrono::seconds(2)); // 模拟一些操作
{
std::lock_guard<std::mutex> lock(mtx);
condition = true;
}
cv.notify_one(); // 通知一个等待的线程
}
int main() {
std::thread t1(waitForCondition);
std::thread t2(notifyCondition);
t1.join();
t2.join();
return 0;
}