Complete guide on how to Pass Arguments to thread and How You Could Use Them With C++

Complete guide on how to Pass Arguments to thread and How You Could Use Them With C++

This blog describes how to pass an argument to a thread and which arguments cannot be passed.

The first thing we’ll look at is why we should be concerned about passed arguments in threads. This may have you wondering, “should I even care?” and “Okay, right? What are these pesky/weird arguments again, and why do I need them?” Phew! We riled up some of you just by mentioning threads and arguments! But, in all seriousness, let us begin at the beginning.

There are two ways of passing arguments to the thread.

  1. Pass by value
  2. pass by reference

Both the methods are described in below example code, where two functions i.e by_value(0 and by_ref() are invoked by two threads.

Note: Use std::ref() while passing parameters by reference. The helper functions ref and cref generate an object of type std::reference wrapper, using template argument deduction to determine the template argument of the result.

#include <iostream>
#include <thread>
#include <chrono>

////////////////////////////// for thread with pass by value
void by_Value(int x, int y)
{
	std::cout << "Thread_1 x + y pass-by value value : " << std::endl;
	std::cout << " X + Y = " << x + y << std::endl;
}

void passByValue()
{
	int p = 9;
	int q = 8;

	std::thread thread_1(by_Value, p, q);

	thread_1.join();
}


////////////////////////////// for thread with pass by ref
void by_ref(int& x)
{
	while (true)
	{
		std::cout << "Thread_1 x value : " << x << std::endl;
		std::this_thread::sleep_for(std::chrono::milliseconds(1000));
	}
}


void passByRef()
{
	int x = 9;
	std::cout << "Main thread current value of X is : " << x << std::endl;
	std::thread thread_1(by_ref, std::ref(x));
	std::this_thread::sleep_for(std::chrono::milliseconds(5000));

	x = 15;
	std::cout << "Main thread X value changed to : " << x << std::endl;
	thread_1.join();
}


int main()
{
	passByValue();
	passByRef();
}

Output:

Thread_1 x + y pass - by value value :
X + Y = 17
Main thread current value of X is : 9
Thread_1 x value : 9
Thread_1 x value : 9
Thread_1 x value : 9
Thread_1 x value : 9
Thread_1 x value : 9
Main thread X value changed to : 15
Thread_1 x value : 15
Thread_1 x value : 15
Thread_1 x value : 15
Thread_1 x value : 15