[英]Is it necessary to acquire the lock and notify condition_variable if no thread needs to wake up?
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)
获取一个 std::mutex(通常通过 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)
在 std::condition_variable 上执行 notify_one 或 notify_all (通知不需要持有锁)
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?如果更改不需要唤醒线程,例如这里的
on_pause
function,为什么需要获取锁(1)或调用通知(3)? (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_; });
}
Your on_pause
function sets pause_
to true, while the predicate in check_pause
verifies that it is set to false.您的
on_pause
function 将pause_
设置为 true,而check_pause
中的谓词验证它是否设置为 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.因此在
on_pause
中调用notify_all
是没有意义的,因为check_pause
中的通知线程将检查谓词并立即 go 回到睡眠状态。 And since pause_
is atomic and you don't need to call notify_all
, you also don't need the lock.而且由于
pause_
是原子的并且您不需要调用notify_all
,因此您也不需要锁。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.