I am reading about std::condition_variable on http://en.cppreference.com/w/cpp/thread/condition_variable and I don\'t understand this:
Even if the sha
Consider this example:
std::atomic_bool proceed(false);
std::mutex m;
std::condition_variable cv;
std::thread t([&m,&cv,&proceed]()
{
{
std::unique_lock l(m);
while(!proceed) {
hardWork();
cv.wait(l);
}
}
});
proceed = true;
cv.notify_one();
t.join();
Here the atomic shared data proceed
is modified without the use of a mutex, after which notification is sent to the condition variable. But it is possible that at the instant that the notification is sent, the thread t
is not waiting on cv
: instead it is inside hardWork()
having checked proceed
just before that and found it to be false. The notification is missed. When t
completes hardWork
, it will resume the wait (presumably forever).
Had the main thread locked the mutex before modifying the shared data proceed
, the situation would have been avoided.
I think this is the situation in mind when saying "Even if the shared variable is atomic, it must be modified under the mutex in order to correctly publish the modification to the waiting thread."