Take this code:
std::condition_variable var;
var.wait(lock, [&sharedBool] { return sharedBool; });
When var
reads from sharedBool, is that thread safe? If it isn't, is making sharedBool
a std::atomic<bool>
reasonable?
Take this code:
std::condition_variable var;
var.wait(lock, [&sharedBool] { return sharedBool; });
When var
reads from sharedBool, is that thread safe? If it isn't, is making sharedBool
a std::atomic<bool>
reasonable?
Reading from sharedBool
happens under the protection of the mutex locked by lock
.
As long as all concurrent accessed to sharedBool
happen while a lock to the same mutex is held, your program is thread-safe.
Since you also cannot wait
on a condition variable without holding a lock, it is usually not reasonable to use an atomic for this use case.
lock
must be acquired before entering this method, and it is reacquired after wait(lock)
exits, which means that lock
can be used to guard access to stop_waiting()
. –
Cover © 2022 - 2024 — McMap. All rights reserved.
{ std::unique_lock<std::mutex> lock{your_mutex}; sharedBool = newvalue; var.notify_all(); }
(or notify_one) to update your bool and trigger an evaluation of the predicate. An extra synchronization primitive will only complicate things. – Guerin