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.

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.

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

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,


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



Python Recommendations:

C++ & C++11 Recommendations:

If you didn't find what you were looking, then do suggest us in the comments below. We will be more than happy to add that.

Subscribe with us to join 1500+ Python & C++ developers, to get more Tips &  Tutorials like this.