Search code examples
c++pthreadsparameter-passingfunction-pointers

Multiple arguments to function called by pthread_create() - argument is function pointer


My case is similar to another Question.

I would like to pass a function as argument and an integer value. Testing the case with a simplfied construction:

void print (int x, int y) 
{ cout << "x = " << x << ", y = " << y << endl; }

void *interrupt (struct arg_struct args);

struct arg_struct { 
    void (*func)(int,int);          // Argument 1
    int a;                          // Argument 2
    int b;                          // Argument 3
};  

int _tmain(int argc, _TCHAR* argv[]){ 

    int a = 1700, b = 1000;

    struct arg_struct arguments;

    arguments.func = print;
    arguments.a = a;
    arguments.b = b;

    (*interrupt)(arguments);

    cin.get(); return 0;
}


void *interrupt (struct arg_struct args) {

    void (*func) (int,int) ;

    func =  args.func;
    int x = args.a;
    int y = args.b;

    (*func)(x,y);

    return 0;           // Erfordert Rückgabewert
}

So now I want to create a thread to execute this passed function.

void *InThread_func(struct arg_struct *);   // Prototype                        

struct arg_struct { 
    void (*func)(int);          // Argument 1
    int IntNumber;              // Argument 2
};

int InThread(void (*func)(int), int IntNumber){
    
    struct arg_struct arguments;
    
    arguments.func   = func;
    arguments.IntNumber = IntNumber;

    // Initialize handler
    pthread_t InThread_thread;
    
    // Create thread
    pthread_create(&InThread_thread,NULL,&InThread_func,(void*) &arguments);
    
    pthread_join(InThread_func,NULL);

    return(errno);
}

Using

g++-4.6 -o test test.cpp

the compiler says

invalid conversion from void* (*)(arg_struct*) to void * (*)(void*)

referring to the last argument of pthread_create.

Why is that?


Solution

  • C++ is picky when it comes to casting.

    Replace void *InThread_func(struct arg_struct *); by void *InThread_func(void *my_data); and it should solve the problem.

    Since this is C++ I'd recommend using std::thread is those are available to you.