Saturday, July 14, 2012

Pthread in c++ class

In pthread API, the pthread_create() takes function which takes a generic pointer and returns a generic pointer. Here is a sample pthread implementation in c

Output:-
In thread....
Message : Hello
Thread exiting...
The problem with pthread_create in c++ is that it can't take member function as a thread function. Because, pthread_create expects a normal function, not a c++ member function. If we pass a member function, then the implicit this pointer won't be available inside this, hence the purpose of member function won't be fulfilled. For this reason, we need to make the thread function static and pass this pointer as object. Inside the function, everything should be accessed through the this pointer. Here is a sample code of pthread_create in C++

Output:-
In Thread...
Message : Hi Hi
Thread exiting...
Here, the problem is we need to write a static member function for every class that needs to use pthread_create(). I have made a wrapper class for this. Here is the code along with how to use it.

Output
Control in Main
In Thread...
Message : Ho Ho
Thread exiting...