Difference between pointer and reference as thread parameter(指针和引用作为线程参数的区别)
问题描述
示例如下:
#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.
这篇关于指针和引用作为线程参数的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:指针和引用作为线程参数的区别
基础教程推荐
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- CString 到 char* 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 初始化列表*参数*评估顺序 2021-01-01
