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

til*_*man 2 c++ multithreading mutex

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

bool bStop = false;

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

void thread2_fun()
{
    bStop = true;
}
Run Code Online (Sandbox Code Playgroud)

Ric*_*ges 14

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

除非你明确告诉编译器应该有一个栅栏,如使用的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;  
} 
Run Code Online (Sandbox Code Playgroud)


Vit*_*meo 9

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

是的,你有一个竞争条件,导致未定义的行为.

您需要使用std::atomic<bool>或保护写入/读取bStop与同步原语,如std::mutex.


相反,(可惜)共同的信念,这标志着bStop作为volatile没有在这里解决任何问题.在volatile预选赛中有无关线程安全.