【发布时间】:2018-07-03 12:18:43
【问题描述】:
我试图向一位同事演示为什么您最好将 const 引用传递给使用以下代码执行只读操作的函数。令我惊讶的是,它会打印“它很安全!”,即使我在另一个线程正在休眠时更改了 passedBool 的值。
我试图找出我是否在某处打错字,编译器是否优化了代码并通过复制传递passedBool 以避免一些开销,或者是否启动另一个线程会创建passedBool 的本地副本。
class myClass
{
public:
myClass(bool& iBool)
{
t = thread(&myClass::myMethod,this,iBool);
}
~myClass()
{
t.join();
}
private:
thread t;
void myMethod(bool& iBool)
{
this_thread::sleep_for(chrono::seconds(1));
if(iBool)
cout << "It's safe!" << endl;
else
cout << "It's NOT safe!!!" << endl;
}
};
void main()
{
bool passedBool = true;
cout << "Passing true" << endl;
myClass mmyClass(passedBool);
cout << "Changing value for false" <<endl;
passedBool = false;
cout << "Expect \"It's NOT safe!!!\"" <<endl;
}
【问题讨论】:
标签: c++ multithreading concurrency