ameerosein ameerosein - 10 months ago 37
C++ Question

How to multithreading a class member function with pthreads?

I'm trying to run a function named

from a class named
in multi threads. i use this code:

rc = pthread_create(&threads[i], NULL, extensionStep, &td[i]);

to call the function and here is the definition of

void* SVAnchor::extensionStep( void *threadarg)

and i got the following error:

error: cannot convert 'SVAnchor::extensionStep' from type 'void* (SVAnchor::)(void*)' to type 'void* (*)(void*)'
rc = pthread_create(&threads[i], NULL, extensionStep, &td[i]);

that shows the problem is converting from type 'void* (SVAnchor::)(void*)' to type 'void* ()(void)'

How to solve this problem?

Thanks all

Answer Source

This should do the job: (After making the function extensionStep static)

rc = pthread_create(&threads[i], NULL, &(SVAnchor::extensionStep), &td[i]);

Or you can create a wrapper function like this:

struct Argument {
    SVAnchor* ptr;
    int* tid;

static void *extensionStepWrapper(void *arg)
    return (((Argument*)arg)->ptr)->extensionStep(((Argument*)arg)->tid);

And use the wrapper:

Argument arg;
arg.ptr = &(class_variable_name); // Use appropriate name (whatever you variable name is for the object of the class SVAnchor)
arg.tid = &(td[i]);

rc = pthread_create(&threads[i], NULL, &(SVAnchor::extensionStepWrapper), &arg);

Note that if you're calling this from inside another member function, you may do this instead:

arg.ptr = this; 

You can also create a method in the class to start the thread:

bool StartThread(int* tid){
      return (pthread_create(&_thread, NULL, extensionStep, tid) == 0);

You might also need to pass the thread as argument of StartThread() function.