demo
- 简单的锁与条件变量实例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <condition_variable>
#include <mutex>
std::mutex mtx;
std::condition_variable cv;
bool ready = false;
void worker() {
std::unique_lock<std::mutex> lock(mtx); // 获取锁并锁定
cv.wait(lock, []{ return ready; }); // 等待时释放锁, 被唤醒时重新获取锁
// 执行任务...
}
void controller() {
std::lock_guard<std::mutex> lock(mtx); // 这个锁会在超出作用域的时候自动释放
ready = true;
cv.notify_all(); // 唤醒所有等待线程
}
NOTE
- 使用
std::lock_guard<std::mutex> lock(mtx);
, 避免手动解锁