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
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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With