问题描述
示例如下:
#include<iostream>
#include<thread>
using namespace std;
void f1(double& ret) {
ret=5.;
}
void f2(double* ret) {
*ret=5.;
}
int main() {
double ret=0.;
thread t1(f1, ret);
t1.join();
cout << "ret=" << ret << endl;
thread t2(f2, &ret);
t2.join();
cout << "ret=" << ret << endl;
}
输出是:
ret=0
ret=5
使用 gcc 4.5.2 编译,带有和不带有 -O2 标志.
Compiled with gcc 4.5.2, with and without -O2 flag.
这是预期的行为吗?
这个程序是免费的数据竞争吗?
Is this program data race free?
谢谢
推荐答案
std::thread 的构造函数推导参数类型并按值存储它们的副本.这需要确保参数对象的生命周期至少与线程的生命周期相同.
The constructor of std::thread deduces argument types and stores copies of them by value. This is needed to ensure the lifetime of the argument object is at least the same as that of the thread.
C++ 模板函数参数类型推导机制从 T& 类型的参数推导类型 T.std::thread 的所有参数都被复制,然后传递给线程函数,以便 f1() 和 f2() 始终使用该副本.
C++ template function argument type deduction mechanism deduces type T from an argument of type T&. All arguments to std::thread are copied and then passed to the thread function so that f1() and f2() always use that copy.
如果您坚持使用引用,请使用 boost::ref() 或 std::ref() 包装参数:
If you insist on using a reference, wrap the argument using boost::ref() or std::ref():
thread t1(f1, boost::ref(ret));
或者,如果您更喜欢简单,请传递一个指针.这就是 boost::ref() 或 std::ref() 在幕后为您做的事情.
Or, if you prefer simplicity, pass a pointer. This is what boost::ref() or std::ref() do for you behind the scene.
这篇关于指针和引用作为线程参数的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)