線程間的通信
std::condition_variable
用於線程間的通信,允許一個線程等待另一個線程發送的通知。
多執行序
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#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::cout << "Thread " << id << " is waiting " << std::endl;
std::unique_lock<std::mutex> lock(mtx);
std::cout << "Thread " << id << " is waiting cv " << std::endl;
cv.wait(lock, [] { return ready; }); // 等待 ready 為 true
std::cout << "Thread " << id <<" is running " << std::endl;
}
void go() {
std::unique_lock<std::mutex> lock(mtx);
ready = true;
cv.notify_all(); // 通知所有等待的線程
}
int main() {
std::thread threads[5];
for (int i = 0; i < 5; ++i) {
threads[i] = std::thread(print_id, i);
}
std::cout << "Main Thread is sleeping " << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(3));
std::cout << "Main Thread is waking up " << std::endl;
go();
for (auto& t : threads) {
t.join();
}
return 0;
}
執行結果:
執行順序解釋:
- main thread 睡覺了
- t3 等待
- t2 等待
- t1 等待
- t4 等待
- t0 等待 且 t3 等待 cv(condition_variable)
- t2 等待 cv
- t1 等待 cv
- t4 等待 cv
- t0 等待 cv
- main thread 起床了,notifyAll
- t0 執行
- t1 執行
- t4 執行
- t2 執行
- t3 執行