Home Item 8 (2/2)- Enhanced support for multithreading(English)
Post
Cancel

Item 8 (2/2)- Enhanced support for multithreading(English)

Inter-thread Communication

std::condition_variable is used for communication between threads, allowing one thread to wait for a notification from another thread.

Multithreading

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; }); // Wait for ready to be true

     std::cout << "Thread " << id <<" is running " << std::endl;
}

 void go() {
     std::unique_lock<std::mutex> lock(mtx);
     ready = true;
     cv.notify_all(); // Notify all waiting threads
}

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


Execution result:

Desktop View

Explanation of execution order:

  1. main thread goes to sleep
  2. t3 is waiting
  3. t2 is waiting
  4. t1 is waiting
  5. t4 is waiting
  6. t0 is waiting and t3 is waiting for cv (condition_variable)
  7. t2 is waiting for cv
  8. t1 is waiting for cv
  9. t4 is waiting for cv
  10. t0 is waiting for cv
  11. main thread wakes up and calls notifyAll
  12. t0 executes
  13. t1 executes
  14. t4 executes
  15. t2 executes
  16. t3 executes

☝ツ☝

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

👈 ツ 👍