views:

170

answers:

1

pthread takes in as its parameter void (start_routine)(void* userPtr), i was hoping i can use std::mem_fun to solve my problem but i cant.

I would like to use the function void * threadFunc() and have the userPtr act as the class (userPtr->threadFunc()). Is there a function similar to std::mem_func that i can use?

+2  A: 

One way is to use a global function that calls your main thread function:

class MyThreadClass {
public:
  void main(); // Your real thread function
};

void thread_starter(void *arg) {
  reinterpret_cast<MyThreadClass*>(arg)->main();
}

Then, when you want to start the thread:

MyThreadClass *th = new MyThreadClass();
pthread_create(..., ..., &thread_starter, (void*)th);

On the other hand, if you don't really need to use pthreads manually, it might be a good idea to have a look at Boost.Thread, a good C++ thread library. There you get classes for threads, locks, mutexes and so on and can do multi-threading in a much more object-oriented way.

sth
thread_started can also be a static function in MyThreadClass.
Eclipse
i would put extern "C" before the function, because pthread is a C function calling your stuff with C calling conventions. not sure what POSIX says about pthread though. maybe it requires it to be able to call C++ functions, but i highly doubt it.
Johannes Schaub - litb
Yes right, that would be even a cleaner solution.
sth
i do something like this, a static function which calls the actual func with S prefixed to the functioname
acidzombie24