gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 10:30:12 27 4
gpt4 key购买 nike

我正在阅读 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 中的谓词验证它是否设置为 false。因此调用 notify_allon_pause毫无意义,因为 check_pause 中的通知线程将检查谓词并立即返回 sleep 状态。自从pause_是原子的,你不需要调用 notify_all ,你也不需要锁。

关于c++ - 如果没有线程需要唤醒,是否需要获取锁并通知condition_variable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62546386/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com