1.测试目标
1.子线程根据传入的参数做出不同的回应
2.传给子线程的参数在主线程中进行更改
#include <iostream>
#include <thread>
using namespace std;
bool flag_global = false;
void fun1(bool flag)
{
while(1)
{
if(flag)
{
cout<<"flag: "<<flag<<endl;
break;
}
else
cout<<"flag: "<<flag<<endl;
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
}
cout<<"子线程结束"<<endl;
}
int main()
{
cout << "主线程开始" << endl;
std::thread th1(fun1, flag_global);
//std::thread th1(fun1, std::ref(flag_global));
while(1)
{
char c= getchar();
//char c='g';
if(c == 'g')
{
flag_global=true;
cout<<"flag_global 在主线程中被置为 true "<<endl;
}
else if(c=='q')
{
break;
cout<<"主线程循环结束"<<endl;
}
std::this_thread::sleep_for(std::chrono::milliseconds(2000));
}
th1.join();
cout << "主线程结束" << endl;
return 0;
}
可以看到,最开始传给子线程是false,在用户输入’g’后,子线程得到的参数是true,执行其他语句.
结果
然而事实上,flag_global在主线程中被赋值为true之后,传入子线程的仍旧是false,
因为,std::thread的参数是按值传递的.如果达到按引用传参的效果,可以使用std::ref
解决方法
void fun1(bool &flag) // 更改为引用
// ...
std::thread th1(fun1, std::ref(flag_global));
结果
可以看到传入的参数被正确的更改了.
参考
https://www.cnblogs.com/5iedu/p/11633683.html