#include #include #include #include #include using namespace std ; mutex mutexObject ; condition_variable cv; bool ready1 = false ; bool ready2 = false ; bool readyMain = false ; void worker_thread1() { cout << "worker_thread1() ...entering.\n"; ready1 = false ; unique_lock lk( mutexObject ); cv.wait(lk, []{ return ready1; }); cout << "worker_thread1() doing some work.\n"; this_thread::sleep_for(chrono::seconds(10)); readyMain = true ; cv.notify_one() ; cout << "worker_thread1() exiting.\n"; } void worker_thread2() { cout << "worker_thread2() ...entering.\n"; ready2 = false ; unique_lock lk( mutexObject ); cout << "worker_thread2() grabbed the lock\n"; cv.wait(lk, []{ return ready2; }); cout << "worker_thread2() doing some work.\n" ; this_thread::sleep_for(chrono::seconds(1)) ; cout << "worker_thread2() exiting.\n" ; } int main() { thread worker1(worker_thread1); thread worker2(worker_thread2); cout << "main thread() waiting for 5 seconds.\n" ; this_thread::sleep_for(chrono::seconds(5)) ; cout << "main thread() sending signal to worker thread 1.\n" ; ready1 = true ; cv.notify_one() ; cout << "main thread() before unique_lock.\n" ; unique_lock lk( mutexObject ); cout << "main thread() waiting for worker thread 1.\n" ; cv.wait(lk, []{ return readyMain; }); cout << "main thread() after waiting for worker thread 1.\n" ; cout << "main thread() waiting for 5 seconds.\n" ; this_thread::sleep_for(chrono::seconds(5)) ; cout << "main thread() sending signal to worker thread 2.\n" ; ready2 = true ; cv.notify_one() ; worker1.join(); worker2.join(); }