<分区>
如果不使用互斥体,下面的源码有什么问题吗?
bool bStop = false;
void thread1_fun()
{
while (!bStop)
{
doSomething();
}
}
void thread2_fun()
{
bStop = true;
}
<分区>
如果不使用互斥体,下面的源码有什么问题吗?
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/