Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between pointer and reference as thread parameter

This is the example:

#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;    } 

And the output is:

ret=0 ret=5 

Compiled with gcc 4.5.2, with and without -O2 flag.

Is this expected behavior?

Is this program data race free?

Thank you

like image 251
Predrag Avatar asked Feb 25 '11 11:02

Predrag


People also ask

Why use a reference instead of a pointer?

References are usually preferred over pointers whenever you don't need “reseating”. This usually means that references are most useful in a class's public interface. References typically appear on the skin of an object, and pointers on the inside.

Can I pass a pointer as reference parameter?

Note: It is allowed to use “pointer to pointer” in both C and C++, but we can use “Reference to pointer” only in C++. If a pointer is passed to a function as a parameter and tried to be modified then the changes made to the pointer does not reflects back outside that function.

How do you reference a pointer in an address?

Memory Address: A pointer has its own memory address and size on the stack, whereas a reference shares the same memory address with the original variable but also takes up some space on the stack. int &p = a; cout << &p << endl << &a; 6.

What is the difference between call by value and call by reference?

In the Call by Value method, there is no modification in the original value. In the Call by Reference method, there is a modification in the original value. In the case of Call by Value, when we pass the value of the parameter during the calling of the function, it copies them to the function's actual local argument.


2 Answers

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

If you insist on using a reference, wrap the argument using boost::ref() or std::ref():

thread t1(f1, boost::ref(ret)); 

Or, if you prefer simplicity, pass a pointer. This is what boost::ref() or std::ref() do for you behind the scene.

like image 154
Maxim Egorushkin Avatar answered Sep 23 '22 03:09

Maxim Egorushkin


If you want to pass parameters by reference to a std::thread you must enclose each of them in std::ref:

thread t1(f1, std::ref(ret)); 

More info here.

like image 27
Matteo Italia Avatar answered Sep 25 '22 03:09

Matteo Italia