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

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.

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Returning a pointer of a local variable C++(返回局部变量 C++ 的指针)
Inline function linkage(内联函数联动)
Which is more efficient: Return a value vs. Pass by reference?(哪个更有效:返回值与通过引用传递?)
Why is std::function not equality comparable?(为什么 std::function 不具有可比性?)
C++ overload resolution(C++ 重载解析)
When to Overload the Comma Operator?(什么时候重载逗号运算符?)