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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值