| 1 | #include <thread> |
|---|---|
| 2 | |
| 3 | #include "baz.h" |
| 4 | |
| 5 | std::condition_variable cv; |
| 6 | std::mutex mutex; |
| 7 | |
| 8 | int bar(int i) { |
| 9 | int j = i * i; |
| 10 | return j; |
| 11 | } |
| 12 | |
| 13 | int foo(int i) { return bar(i); } |
| 14 | |
| 15 | void compute_pow(int &n) { |
| 16 | std::unique_lock<std::mutex> lock(mutex); |
| 17 | n = foo(i: n); |
| 18 | lock.unlock(); |
| 19 | cv.notify_one(); // waiting thread is notified with n == 42 * 42, cv.wait |
| 20 | // returns |
| 21 | } |
| 22 | |
| 23 | void call_and_wait(int &n) { baz(j&: n, mutex, cv); } |
| 24 | |
| 25 | int main() { |
| 26 | int n = 42; |
| 27 | std::thread thread_1(call_and_wait, std::ref(t&: n)); |
| 28 | std::thread thread_2(compute_pow, std::ref(t&: n)); |
| 29 | |
| 30 | thread_1.join(); |
| 31 | thread_2.join(); |
| 32 | |
| 33 | return 0; |
| 34 | } |
| 35 |
