指针和引用作为线程参数的区别

示例如下:

#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.

相关文章