Thread: How to pass arguments to a thread?
Source File is here.
Hey welcome folks.
In last article we saw how to create a thread using C++11 and how to synchronize two threads and print even and odd numbers in different thread. If you missed, you can check here.
In this article we will see how to pass an argument to a thread. And more importantly how not to pass an argument to a thread.
Let’s begin.
We already know how to create a thread. Here we have 3 functions fun1(), fun2() and fun3().
int fun1( const string str);
int fun2(int x);
int fun3(int &x);
fun1() takes a const string as a parameter and fun2() takes a integer value and fun3() takes a integer referance.
In main(), lets create a thread t1 with function pointer fun1() and pass a string literal.
std::thread t1(fun1, "I am in Thread1.");
This will print “I am in Thread1” at output.
Now lets create a thread t2 with function fun2() and pass a integer variable ‘x’.
std::thread t2(fun2, (x));
Here we are passing an integer variable x by value. Notice here that thread will create a local copy of this variable and do all the operation on the local copy of x. Changes on variable will not reflect on the x in main thread which we passed as a parameter.
Lets create a new thread t3 . In c++11 to pass a referenceto a thread, we have std::ref().
std::thread t3(fun3, std::ref(x));
In this statement we are passing reference of x to thread t3 because fun3() takes int reference as a parameter. If we try to pass ‘x’ or ‘&x’ it will throw a compile time error.
If you want to see error, uncomment below line
//std::thread t3(fun3, (&x));
Now we will create dynamic memory and will try to pass to thread in different ways.
int*p = new int(99);
Uncomment below lines and see the error. Each lines will give you same error, I hope
//std::thread t4(fun2, p);
//std::thread t4(fun2, *p);
//std::thread t5(fun2, std::ref(p));
In order to send a dynamic allocated memory we will have to pass it as below
std::thread t6(fun3, std::ref(*p));
I hope you did not forget to join all threads which you are using. Failing to join thread may behave surprisingly or crush your program.
At last we are printing ‘x’ and ‘*p’.
cout << "main() x: "<<x << endl;
cout << "main() *p: "<<*p << endl;
You can check when values are updating. Threads which are running fun2() are creating a local copy of variable and do not update the values in main() but threads which are running fun3() are updating values of variables in main().
This is a one way we can return a value from a thread. C++11 provides a spacial way to return a value from a thread is std::future and std::promise.
Next time we will see how C++11 do this.