我可以在没有互斥量的线程中读取bool变量吗? [英] Can I read a bool variable in a thread without mutex?

查看:67
本文介绍了我可以在没有互斥量的线程中读取bool变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我不使用互斥锁,那么以下源代码有什么错误吗?

Is there anything wrong in following source code if I don't use mutex?

bool bStop = false;

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

void thread2_fun()
{
    bStop = true;
}

推荐答案

在一个线程中写入对象而另一个线程完全访问对象时,这是未定义的行为.

It is undefined behaviour to write to an object in one thread while another thread accesses the object at all.

除非您明确告知编译器应该有围栏,例如使用std::atomicstd::mutex等,否则所有投注都将关闭.

Unless you specifically inform the compiler that there should be a fence, such as the use of std::atomic, std::mutex et al, all bets are off.

编译器有权按以下方式重新编写代码:

The compiler is within its rights to re-write the code as this:

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;  
} 

这篇关于我可以在没有互斥量的线程中读取bool变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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