Reputation: 389
I was reading this reference and saw:
The thread that intends to modify the variable has to
acquire a std::mutex (typically via std::lock_guard)
perform the modification while the lock is held
execute notify_one or notify_all on the std::condition_variable (the lock does not need to be held for notification)
If the change doesn't need to wake up threads, like on_pause
function here, why is acquiring the lock (1) or calling notify (3) necessary? (Just waking them up to say good night?)
std::atomic<bool> pause_;
std::mutex pause_lock_;
std::condition_variable pause_event_;
void on_pause() // part of main thread
{
// Why acquiring the lock is necessary?
std::unique_lock<std::mutex> lock{ pause_lock_ };
pause_ = true;
// Why notify is necessary?
pause_event_.notify_all();
}
void on_resume() // part of main thread
{
std::unique_lock<std::mutex> lock{ pause_lock_ };
pause = false;
pause_event_.notify_all();
}
void check_pause() // worker threads call this
{
std::unique_lock<std::mutex> lock{ pause_lock_ };
pause_event_.wait(lock, [&](){ return !pause_; });
}
Upvotes: 1
Views: 414
Reputation: 2949
Your on_pause
function sets pause_
to true, while the predicate in check_pause
verifies that it is set to false. Hence calling notify_all
in on_pause
is pointless, because the notified threads in check_pause
will check the predicate and immediately go back to sleep. And since pause_
is atomic and you don't need to call notify_all
, you also don't need the lock.
Upvotes: 0