In the period before Thread A expects a condition variable, it must contain a mutex. The easiest solution is to make sure that Thread B has the same mutex at the time it calls notify_all. So something like this:
std::mutex m; std::condition_variable cv; int the_condition = 0; Thread A: { std::unique_lock<std::mutex> lock(m); do something while (the_condition == 0) { cv.wait(lock); } now the_condition != 0 and thread A has the mutex do something else }
This ensures that Thread B will execute notify_all () only before Thread A receives the mutex or while Thread A expects a condition variable.
Another key here, however, is the while loop, which expects the condition to become true. After A has a mutex, it should not be possible for any other thread to change the condition until A checks the_condition, finds it false and starts to wait (thus freeing up the mutex).
The fact is that you really expect the_condition to become non-zero, std :: condition_variable :: notify_all just tells you that thread B believes that thread A should wake up and test.
source share