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:
Explanation of execution order:
- main thread goes to sleep
- t3 is waiting
- t2 is waiting
- t1 is waiting
- t4 is waiting
- t0 is waiting and t3 is waiting for cv (condition_variable)
- t2 is waiting for cv
- t1 is waiting for cv
- t4 is waiting for cv
- t0 is waiting for cv
- main thread wakes up and calls notifyAll
- t0 executes
- t1 executes
- t4 executes
- t2 executes
- t3 executes

