Dec 9, 2009

Thread call on class method

It is very strange for C++. When you want to fork another thread, which runs on a class method, you cannot invoke pthread_create() because C++ does not a class method of type void* start_routine)(void*) to be "deferenced".

Here is the signature of pthread_create();

int pthread_create
(
  pthread_t *thread,
  const pthread_attr_t *attr,
  void * (*start_routine)(void*),
  void *arg
);


To work arounde this problem, we must declare a class method to be a static class method, which is allowed to be deferenced. Then, we pass the instance of the class as arg. Then, inside the static method, we invoke the wanted class method.

Here is an example:

class Test
{
  private:

    void _StartDoing()
    {
      // do something
    };

    static void* _ThreadStartDoing(void *obj)
    {
      reinterpret_cast<test *>(obj)->_StartDoing();
    };
}


And when you want to fork a thread, inside Test:

pthread_create( &pid, 0, &Test::_ThreadStartDoing, this);


And that is it.