Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top