https://gcc.gnu.org/bugzilla/show_bug.cgi?id=110016

--- Comment #16 from Jonathan Wakely <redi at gcc dot gnu.org> ---
The condition variable uses that mutex to synchronize. If you just modify the
atomic variable _without locking and unlocking the mutex_ then you are not
synchronizing with the condition variable.

If you don't use the mutex for the producer thread, then (as Andrew described)
the consumer can check the atomic, see that the condition is not yet true, and
decide it needs to wait. Then the producer makes the condition true and signals
using notify_all but that is missed because the consumer thread isn't waiting
yet, then the consumer starts to wait. But because it already missed the
notify_all call, it waits forever.

Using the mutex in the producer does not just hide the bug, it fixes it
properly. If the producer updates the atomic while the mutex is held then it's
impossible for the condition to become true between the consumer checking it
and starting to wait. Those two things (checking the condition and starting to
wait) become atomic w.r.t the producer. It's not possible to get this
interleaving if you use the mutex correctly:

consumer checks condition
producer makes condition true
producer notifies
consumer waits

Instead you either get:

consumer checks condition and waits
producer makes condition true and notifies, waking the consumer

or:

producer makes condition true (and notifies, but consumer isn't waiting)
consumer sees condition is true and never waits

Reply via email to