【问题标题】:Is it necessary to acquire the lock and notify condition_variable if no thread needs to wake up?如果没有线程需要唤醒,是否需要获取锁并通知condition_variable?
【发布时间】:2020-10-14 04:49:36
【问题描述】:

我正在阅读 this reference 并看到:

打算修改变量的线程必须

  1. 获取一个 std::mutex(通常通过 std::lock_guard)

  2. 在持有锁时执行修改

  3. 在 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


【解决方案1】:

您的on_pause 函数将pause_ 设置为true,而check_pause 中的谓词验证它是否设置为false。因此在on_pause 中调用notify_all 是没有意义的,因为check_pause 中的通知线程将检查谓词并立即返回睡眠状态。由于pause_ 是原子的,你不需要调用notify_all,你也不需要锁。

【讨论】:

    猜你喜欢
    • 2012-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-14
    相关资源
    最近更新 更多