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. Any threa
I don't think Sam`s answer is correct. Consider the following code:
// thread #1:
std::unique_lock l(m);
while (!proceed) cv.wait(l);
// thread #2:
proceed = true; // atomic to avoid data race
cv.notify_one();
The problem here is the following possible sequence of events:
thread #1: while (!proceed) // evaluated as true
thread #2: proceed = true;
thread #2: cv.notify_one();
thread #1: cv.wait(l); // never gets notified
To avoid this scenario, a typical solution is to protect modification of proceed
with the same mutex:
// thread #1:
std::unique_lock l(m);
while (!proceed) cv.wait(l);
// thread #2:
{
std::lock_guard l(m);
proceed = true; // does not need to be atomic
}
cv.notify_one();
Now, proceed = true;
must happen either before while (!proceed)
or after cv.wait(l);
starts waiting; both is ok. In the first case, there is no waiting at all; in the second case, cv.notify_one();
is guaranteed to happen only when cv.wait(l);
is actually waiting.
Now, what about your (kind-of academic) case?
// thread #1:
std::unique_lock l(m);
while (!proceed) cv.wait(l);
// thread #2:
proceed = true; // atomic to avoid data race
{
std::lock_guard lock(m);
}
cv.notify_one();
I believe this case is also perfectly valid, since the above-described wrong scenario cannot happen as well. For simple reason. If while (!proceed)
is evaluated as false, again, there is no waiting. And, if while (!proceed)
is evaluated as true, then notification cannot happen until cw.wait(l);
is invoked.
Conclusion
I believe your first example is ok and the quote from cppreference is incorrect.