概括

使用 std::condition_variable 的 wait 会把目前的线程 thread 停下来并且等候事件通知,而在另一个线程中可以使用 std::condition_variable 的 notify_one 或 notify_all 发送通知那些正在等待的事件

用法

1
2
3
4
5
6
condition_variable 常用成员函数:
- wait:阻塞当前线程直到条件变量被唤醒
- notify_one:通知一个正在等待的线程
- notify_all:通知所有正在等待的线程

使用 wait 必须搭配 std::unique_lock<std::mutex> 一起使用

用例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <string>
#include <thread>
#include <mutex>
#include <condition_variable>

std::mutex m;
std::condition_variable cv;

void worker_thread()
{
std::unique_lock<std::mutex> lock(m);
std::cout << "worker_thread()等待唤醒\n";
cv.wait(lock);

std::cout << "worker_thread()已被唤醒\n";
}

int main()
{
std::thread worker(worker_thread);

std::this_thread::sleep_for(std::chrono::milliseconds(5));
std::cout << "main()唤醒线程\n";
cv.notify_one();

worker.join();
std::cout << "main()结束\n";
}