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

标签 c++ multithreading locking condition-variable

我正在阅读 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/

相关文章:

c++ - 从时间 std::strings boost ptime

multithreading - 如何管理服务器上的数据库连接?

linux - save_stack_trace_tsk 和 struct stack_trace 在 Linux 5.2+ 中不再可用

c - 如果需要调用copy_to_user,如何使用自旋锁?

c++ - 我需要对分配给另一个指针的指针调用 delete 吗?

c++ - 如何在不使用全局变量的情况下在函数之间使用多个变量?

c++ - c++ 中的线程不会在 mandelbrot 图像处理上产生加速

java - 带有 ReentrantLock 的 Java 竞争条件

java - 简单Java服务中的并发问题

c++ - 为什么在 ColMajor MappedSparseMatrix 上调用 .row() 方法会失败?