You need to use a method that takes void*
because it's called by pthread library, and pthread library passes your method a void*
- the same pointer that you pass pthread_create
as the last parameter.
Here is an example of how you can pass arbitrary parameters to a thread using a single void*
:
struct my_args {
char *name;
int times;
};
struct my_ret {
int len;
int count;
};
void * PrintHello(void *arg) {
my_args *a = (my_args*)arg;
for (int i = 0 ; i != a->times ; i++) {
cout << "Hello " << a->name << endl;
}
my_ret *ret = new my_ret;
ret->len = strlen(a->name);
ret->count = strlen(a->name) * a->times;
// If the start_routine returns, the effect is as if there was
// an implicit call to pthread_exit() using the return value
// of start_routine as the exit status:
return ret;
}
...
my_args a = {"Peter", 5};
pthread_create(&mpthread, NULL, PrintHello, &a);
...
void *res;
pthread_join(mpthread, &res);
my_ret *ret = (my_ret*)(*res);
cout << ret->len << " " << ret->count << endl;
delete ret;
Even though your function does not want to take any arguments or return anything, since pthread library passes it parameters and collects its return value, your function needs to have the appropriate signature. Passing a pointer to a void
function that takes no parameters in place of a void*
function that takes one parameter would be undefined behavior.