Reading the text for std::condition_variable I've come across this sentence:
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.
My question is this:
What is the use for atomics if not for "lock-free code to work with PODs"?
UPDATE
Looks like there's some confusion about my question :(
The "shared variable" in the quoted text is not the same as "condition variable". See this quote from the same page:
... until another thread both modifies a shared variable (the condition), and notifies the condition_variable
Please do not answer "why we need to use a mutex with condition variables" or "how the conditional wait works" but rather provide information on how the use of a mutex "correctly publishes" the modification of an atomic to the waiting thread, i.e. whether an expression like ++counter; (not the test like if(counter == 0)) would need to be done under mutex?
The semantics of a conditional wait necessitates the use of a mutex.
This is because there is a potential race condition on the thread that is testing the condition. When this thread is checking whether to wait, the following happens:
either:
a) release lock and wait for next signal
b) keep lock and continue
Because step 1 acquires a lock, the whole thing is atomic, provided all other parties use the mutex correctly.
But what about when the variable being modified is an atomic?
Well, here's why. If thread B comes along and modifies the atomic outside of the mutex, then steps 2 and 3 are no longer atomic. Essentially, thread B can modify the value immediately after step 2 happens. Then thread A will potentially make an incorrect decision in step 3.