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