condition_variable.notify 是同步点吗? [英] Is condition_variable.notify a synchronization point?

查看:34
本文介绍了condition_variable.notify 是同步点吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这样的事情:

bool signalled = false;
std::condition_variable cv;
void thread1() {
  while (true) {
    std::unique_lock l(mutex);
    cv.wait_until(l, [] { return signalled; });
    return;
  }
}

void thread2...N() {
  signalled = true;
  cv.notify_all();
}

这被认为是线程安全的吗?布尔值可能在许多线程中设置为 true 以中断线程 1.

Is that considered thread-safe? The boolean may be set to true in many threads to interrupt thread1.

如果不是线程安全的,我正在寻找竞争条件的描述,以便我可以更好地理解潜在问题并填补知识空白.

If not thread-safe I’m looking for a description of what the race condition is so I can better understand the underlying issue and fill in a knowledge gap.

推荐答案

在没有同步的情况下写入非原子变量是 UB.但是,将 signaled 设为 atomic 并不能解决问题.

Writing to a non-atomic variable without synchronization is UB. However, making signalled an atomic<bool> will not solve the problem.

C++ 参考关于std::condition_variable 读:

即使共享变量是原子的,也必须在互斥锁下进行修改,才能将修改正确发布到等待线程.

Even if the shared variable is atomic, it must be modified under the mutex in order to correctly publish the modification to the waiting thread.

你应该这样做:

bool signalled = false;

void thread2...N()
{
    std::unique_lock l(mutex);
    signalled = true;
    cv.notify_all();
}

相关问题:

这篇关于condition_variable.notify 是同步点吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆