#include #include #include #include #include using namespace std ; mutex mutexObject ; condition_variable cv; bool ready = false; bool processed = false; void worker_thread() { cout << "Worker thread starting.\n"; // Wait until main() sends signal unique_lock lk( mutexObject ); cout << "worker thread about to acquire the lock.\n" ; //ready = true ; //It has locked the lock. Wait needs the lock to be //locked. this_thread::sleep_for(chrono::seconds(5)); //wait releases the lock. Once we get a notify we //will acquire the lock again if it is free. cv.wait(lk, []{ return ready; }); // after the wait, we own the lock. cout << "Worker thread is processing after wait.\n"; cout << "Worker thread signals dtr1 processing completed\n"; // Manual unlocking is done before notifying, to avoid waking up // the waiting thread only to block again (see notify_one for details) lk.unlock(); processed = true; cv.notify_one(); } int main() { //worker thread starts and waits for a signal from the //main thread thread worker(worker_thread); { //Let the thread lock first //this_thread::sleep_for(chrono::seconds(5)); lock_guard lk(mutexObject); cout << "main() signals worker thread ready to start.\n"; //Is ready enough to unblock worker thread ? // //this_thread::sleep_for(chrono::seconds(10)); ready = true; cv.notify_one(); //The worker thread cannot proceed at this stage //because the lock has not been freed. After the next //lines the lock guard will go out of scope this_thread::sleep_for(chrono::seconds(30)); cout << "main() about to release the lock guard.\n" ; } //cv.notify_one(); // wait for the worker { cout << "Inside main() waiting for the worker thread. Step 1 \n"; unique_lock lk(mutexObject); cout << "Inside main() waiting for the worker thread. Step 2 \n"; //this_thread::sleep_for(chrono::seconds(5)); cv.wait(lk, []{ return processed; }); } cout << "Back in main()" << '\n'; worker.join(); }