您需要使用一个方法,void*
因为它由 pthread 库调用,并且 pthread 库传递您的方法 a - 您作为最后一个参数void*
传递的指针相同。pthread_create
这是一个示例,说明如何使用单个 将任意参数传递给线程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;
即使您的函数不想接受任何参数或返回任何内容,由于 pthread 库向其传递参数并收集其返回值,您的函数也需要具有适当的签名。将指针传递给void
不带参数的void*
函数而不是带一个参数的函数将是未定义的行为。