【发布时间】:2020-10-14 04:49:36
【问题描述】:
我正在阅读 this reference 并看到:
打算修改变量的线程必须
获取一个 std::mutex(通常通过 std::lock_guard)
在持有锁时执行修改
在 std::condition_variable 上执行 notify_one 或 notify_all(通知不需要持有锁)
如果更改不需要唤醒线程,例如这里的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_; });
}
【问题讨论】:
-
这是你的问题吗:: 为什么需要通知?
-
@asmmo 为什么需要获取锁?为什么需要通知?
标签: c++ multithreading locking condition-variable