我正在阅读 this reference并看到:
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)
如果更改不需要唤醒线程,如
on_pause
函数在这里,为什么需要获取锁(1)或调用通知(3)? (只是叫醒他们说晚安?)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_; });
}
最佳答案
您的 on_pause
功能集pause_
为真,而 check_pause
中的谓词验证它是否设置为 false。因此调用 notify_all
在 on_pause
毫无意义,因为 check_pause
中的通知线程将检查谓词并立即返回 sleep 状态。自从pause_
是原子的,你不需要调用 notify_all
,你也不需要锁。
关于c++ - 如果没有线程需要唤醒,是否需要获取锁并通知condition_variable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62546386/