Home Item 8 (2/2)- 多線程支持的增強(中文)
Post
Cancel

Item 8 (2/2)- 多線程支持的增強(中文)

線程間的通信

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;
}


執行結果:

Desktop View

執行順序解釋:

  1. main thread 睡覺了
  2. t3 等待
  3. t2 等待
  4. t1 等待
  5. t4 等待
  6. t0 等待 且 t3 等待 cv(condition_variable)
  7. t2 等待 cv
  8. t1 等待 cv
  9. t4 等待 cv
  10. t0 等待 cv
  11. main thread 起床了,notifyAll
  12. t0 執行
  13. t1 執行
  14. t4 執行
  15. t2 執行
  16. t3 執行

☝ツ☝

This post is licensed under CC BY 4.0 by the author.

👈 ツ 👍