Using pthread in a C++ class, having thread function a member function

Recently we faced an issue of calling a pthread from within the class. Normally in C programming when using pthread, the pthread_create method takes the second argument as the thread entry function, i.e. the function which will run forever in the thread unless stopped. The address of the function is passed, but since the function name itself is the address of the function, hence just the name is specified.
e.g.

pthread_create(&m_threads, NULL, threadFunction, NULL);

To achieve the similar thing in C++ having the thread function as a member function, the problem is faced with the address of the method. C++ assumes that the thread function should be static and able to run independently. So a static function within the class is expected. Since static function cannot invoke members which are non static, therefore we need the following solution.

pthread_create(&m_thread, 0, &CClass::threadFunction, this); 
                                        //threadFunction is static member function

static void* threadFunction(void *obj); // definition in the class
void* CClass::threadFunction(void *obj)
{
reinterpret_cast< CClass *> (obj)->whileOne();
return NULL;
}

void whileOne();                        // public member function
void CClass::whileOne()                 // definition of thread-able function
{
pthread_mutex_lock(&m_mutex);
pthread_mutex_unlock(&m_mutex);
}

That is, we define a static function, accepting a void pointer. Than using this method we create our pthread, passing the last argument as this pointer. Later we cast the void pointer to obtain this pointer again using reinterpret_cast. Since now we have obtained this pointer, we can call member function from within the static method.

Enjoy pthread-ing :)

Comments

Popular posts from this blog

Imote2 with Camera setup IMB400 over Ubuntu 9.10/10.04

Branch and bound algorithm in C#- Article by AsiF Munir

Tensorflow - Simplest Gradient Descent using GradientDescentOptimizer