35 lines · cpp
1#include <thread>2 3#include "baz.h"4 5std::condition_variable cv;6std::mutex mutex;7 8int bar(int i) {9 int j = i * i;10 return j;11}12 13int foo(int i) { return bar(i); }14 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.wait20 // returns21}22 23void call_and_wait(int &n) { baz(n, mutex, cv); }24 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