Posts

Showing posts from March, 2010

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