POSIX Library provides a function pthread_create() to create threads i.e.

It accepts a function pointer as startup routine. This function accepts void * as argument and returns void *. In previous article we discussed how to use this API with global functions to start thread i.e.

POSIX : How to create a thread using pthread_create()

In this article we will discuss how to pass class member functions to pthread_create as startup routine for the thread.

Suppose we have a class Task and it has two member functions, one static and another non static i.e.

Now will see how to create a pthread using both static and non static function of class Task.

Passing non static member function to pthread_create()

class Task and it has a non static function execute() i.e.

Now we want to pass this member function Task::execute() as thread function in pthread_create(). As pthread_create() accepts a function pointer as an argument of following type i.e.

So, typecast Task::execute with type. Also, as compiler pass the pointer of class (this pointer) as first argument in every member function. So, pass pointer to the object of class Task as an argument i.e.

Passing Static member function to pthread_create()

Suppose we have a static function in class Task i.e.

To pass a static member function in pthread_create(), type case it as above i.e. with,

void * (*)( void *)

But as static functions are not associated with any object and therefore compiler doesn’t pass this pointer to it. So, we do’t need to pass any pointer as argument. Just pass NULL i.e.

Complete example is as follows,


To compile the above code use following command,

g++ example.cpp -lpthread


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.