

Dheeraj Jha
Jun 29, 20205 min read


Dheeraj Jha
May 3, 20204 min read


Dheeraj Jha
Apr 25, 20204 min read


Dheeraj Jha
Mar 13, 20202 min read


Dheeraj Jha
Mar 4, 20203 min read

Updated: May 1, 2020
Source File is here.
Hey welcome folks.
In the 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 a different thread. If you missed, you can
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, func2() takes an integer value and fun3() takes an integer reference.
In main(), let's 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 the output.
Now let's create a thread t2 with function fun2() and pass an 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 a variable will not reflect on the x in the main thread which we passed as a parameter.
Let's create a new thread t3. In c++11 to pass a reference, 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 an 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 line will give you the same error, I hope
//std::thread t4(fun2, p);
//std::thread t4(fun2, *p);
//std::thread t5(fun2, std::ref(p));
To send a dynamically 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 one way we can return a value from a thread. C++11 provides a special way to return a value from a thread is std::future and std::promise.
Next time we will see how C++11 do this.










Comments