Accoding to cppreference.com:
The thread that intends to modify the variable has to
- acquire a std::mutex (typically via std::lock_
Found a very good explanation about this issue in another thread. Take a loot at
Questions where asked below about race conditions.
If the data being communicated is atomic, can't we do without the mutex on the "send" side?
at the end.
As noted in Yakk's answer to the question you linked to it is to protect against this sequence of events causing a missed wake-up:
m_hasEvents.load(std::memory_order_relaxed);
and returns the value false
. s_hasEvent
s_cv.notify_one()
. false
result returned by the closure, deciding there are no pending events. This means the notify_one()
call has been missed, and the condition variable will block even though there is an event ready in the queue.
If the update to the shared variable is done while the mutex is locked then it's not possible for the step 4 to happen between steps 2 and 7, so the condition variable's check for events gets a consistent result. With a mutex used by the publisher and the consumer either the store to s_hasEvent
happens before step 1 (and so the closure loads the value true
and never blocks on the condition variable) or it happens after step 8 (and so the notify_one()
call will wake it up).