Goal: In this tutorial, we will see how we can pass the parameters to the function called using thread.
We will create two threads t1 and t2. One thread will call function1 (this function will perform the addition of two numbers), and another thread will call function2 (this function will perform the multiplication of two numbers).
Below is the code for this exercise:
using namespace std;
int multi;//variable to store the multiplication of two numbers
int sum; //variable to store the sum of two numbers
void function1(int x, int y)
sum = x+y;
void function2(int x, int y)
multi = x*y;
int a = 10, b = 20;
cout<<"Sum of given numbers: "<<sum<<endl;
cout<<"Multiplication of given numbers: "<<multi<<endl;
std::thread object takes two types of parameter,
- Function name
- Values that we want to pass to the called function.
So std::thread t1(function1,a,b) creates the thread t1 and calls the function1 with parameter a and b.
Once the execution of t1 and t2 completes, both the threads are joined to the main thread using join() function/method and we print the output of function1 and function2 using global variables sum and multi.