如果没有线程需要唤醒,是否需要获取锁并通知condition_variable?

Is it necessary to acquire the lock and notify condition_variable if no thread needs to wake up?

我正在阅读 this reference 并看到:

The thread that intends to modify the variable has to

  1. acquire a std::mutex (typically via std::lock_guard)

  2. perform the modification while the lock is held

  3. 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 中的谓词验证它是否设置为假。因此在 on_pause 中调用 notify_all 是没有意义的,因为 check_pause 中的通知线程将检查谓词并立即返回休眠。因为 pause_ 是原子的,你不需要调用 notify_all,你也不需要锁。