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

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.

这篇关于指针和引用作为线程参数的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)
STL BigInt class implementation(STL BigInt 类实现)
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)