C++11 : Start thread by member function with arguments

In this article we will discuss how to start a thread by a member function of class.

Starting thread with non static member function

Suppose we have a class Task, which has non static member function execute() i.e.

class Task
{
public:
	void execute(std::string command);
};

Now we want to start a thread which uses execute() function of the class Task as thread function.

As execute() is a non static function of class Task, so first of all we need a object to call this function. Let’s create an object of class Task i.e.

Task * taskPtr = new Task();

Now let’s create a Thread that will use this member function execute() as thread function through its object i.e.

// Create a thread using member function
std::thread th(&Task::execute, taskPtr, "Sample Task");

Here in std::thread constructor we passed 3 arguments i.e.

1.) Pointer to member function execute of class Task
When std::thread will internally create a new thread, it will use this passed member function as thread function. But to call a member function, we need a object.

2.) Pointer to the object of class Task
As a second argument we passed a pointer to the object of class Task, with which above member function will be called. In every non static member function, first argument is always the pointer to the object of its own class. So, thread class will pass this pointer as first argument while calling the passed member function.

3.) String value
This will be passed as second argument to member function i.e. after Task *

Checkout complete example as follows,

#include <iostream>
#include <thread>

class Task
{
public:
	void execute(std::string command)
	{
		for(int i = 0; i < 5; i++)
		{
			std::cout<<command<<" :: "<<i<<std::endl;
		}
	}

};

int main()
{
	Task * taskPtr = new Task();

	// Create a thread using member function
	std::thread th(&Task::execute, taskPtr, "Sample Task");

	th.join();

	delete taskPtr;
	return 0;
}

Output:

Sample Task :: 0
Sample Task :: 1
Sample Task :: 2
Sample Task :: 3
Sample Task :: 4

Starting thread with static member function

As static functions are not associated with any object of class. So, we can directly pass the static member function of class as thread function without passing any pointer to object i.e

#include <iostream>
#include <thread>

class Task
{
public:
	static void test(std::string command)
	{
		for(int i = 0; i < 5; i++)
		{
			std::cout<<command<<" :: "<<i<<std::endl;
		}
	}

};

int main()
{
	// Create a thread using static member function
	std::thread th(&Task::test, "Task");

	th.join();
	return 0;
}

Output

Task :: 0
Task :: 1
Task :: 2
Task :: 3
Task :: 4

 

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top