c++ - 我可以在没有互斥量的线程中读取 bool 变量吗?

标签 c++ multithreading mutex

<分区>

如果不使用互斥体,下面的源码有什么问题吗?

bool bStop = false;

void thread1_fun()
{
    while (!bStop)
    {
        doSomething();
    }
}

void thread2_fun()
{
    bStop = true;
}

最佳答案

在一个线程中写入一个对象而另一个线程完全访问该对象是未定义的行为。

除非你特别通知编译器应该有栅栏,比如使用std::atomic, std::mutex等,所有的赌注都是关闭。

编译器有权将代码重写为:

bool bStop = false;

void thread1_fun()
{
    const bool stopped = bStop;
    // compiler reasons: "because there is no fence, the variable clearly cannot
    // have changed to true, since no-other thread will modify it, since
    // to modify it without a fence would be UB." 
    while (!stopped)  
    {  
        doSomething();
    }
}

void thread2_fun()
{
    // this happens in my thread's view of the world, 
    // but no other thread need see it.
    bStop = true;  
} 

关于c++ - 我可以在没有互斥量的线程中读取 bool 变量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47867789/

相关文章:

c++ - 解包方法参数的元组

java - 将应用程序链接到 Swing GUI 的最佳方式是什么?

ios - 动画阻止其他 UI 元素响应

linux - 在 Linux 内核中,我可以解锁计时器处理程序中的互斥量吗?

c# - 如何在异步方法中管理互斥体

c++ - 关于特定接口(interface)类型的模板分支

c++ - 使用 dtl-cpp 调用没有匹配的函数

c++ - WaitForSingleObject 未锁定,仍允许其他线程更改 C++ 中的值

c++ - QT多线程和更新GUI