Pass class method as pthread start function

Given the following class

class Foo
{
    public:
        void* func(void* arg)
        {
            // how to pass this function to pthread...?!
        }
}

Later I want to pass func()in pthread_create()instead of a function:

int main()
{
    char * msg = "Hi dude";
    Foo * ins = new Foo();
    pthread_t pt;
    // how to pass ins->func instead of a function?
    pthread_create( &pt, NULL, ins->func, (void*)msg );
}

Thanks in advance.

+3
source share
3 answers

A β€œnormal” approach is to pack the object and all the arguments of the function into a structure, allocate this structure on the heap, pass an instance of this structure to a function with C binding, and allow this function to call the member function of the object

struct wrap {
    char * msg;
    Foo ins; 

    wrap( char* m, const Foo& f ) : msg(m), ins(f) {}
};

extern "C" void* call_func( void *f )
{
    std::auto_ptr< wrap > w( static_cast< wrap* >( f ) );
    w->ins.func(w->msg);

    return 0;
}

int main() {
    wrap* w = new wrap( "Hi dude", Foo() );
    pthread_t pt;

    pthread_create( &pt, NULL, call_func, w );
}
+4
source

This does not work the way you tried , because C ++ member members get a this-stream of the object passed as the first argument. This is implicitly performed by the compiler if in C ++ mode.

pthread_create() C. - " , void * ( void *)". - pthread_create() this, , this ... - -, - - .

pthread_create() , "C": - ( this).

Torsten . .

+4

One way to do this is to declare the function static

#include <iostream>
#include <pthread.h>
class Foo {
  public:
    static void* func(void* arg) {
      char *test = (char *) arg;
      std::cout << test << std::endl;
    }
};
int main() {
  char * msg = "Hi dude";
  Foo ins;
  pthread_t pt;
  pthread_create( &pt, NULL, ins.func, (void*)msg );
  pthread_join(pt, NULL);
  return 0;
}
+2
source

All Articles