pthread中函数的参数个数

在ploread的hello world示例中说明:

#include  #include  void * print_hello(void *arg) { printf("Hello world!\n"); return NULL; } int main(int argc, char **argv) { pthread_t thr; if(pthread_create(&thr, NULL, &print_hello, NULL)) { printf("Could not create thread\n"); return -1; } if(pthread_join(thr, NULL)) { printf("Could not join thread\n"); return -1; } return 0; } 

正如您所看到的, pthread_create() print_hello没有参数,但是在定义中,它看起来像void * print_hello(void *arg)

那是什么意思?

现在假设我有这个实现

 void * print_hello(int a, void *); int main(int argc, char **argv) { pthread_t thr; int a = 10; if(pthread_create(&thr, NULL, &print_hello(a), NULL)) { printf("Could not create thread\n"); return -1; } .... return 0; } void * print_hello(int a, void *arg) { printf("Hello world and %d!\n", a); return NULL; } 

现在我收到此错误:

 too few arguments to function print_hello 

那么我该如何解决这个问题呢?

pthread将一个类型为void *参数传递给线程函数,因此您可以将指针传递给您想要的任何类型的数据作为pthread_create函数的第四个参数,请查看下面修复代码的示例。

 void * print_hello(void *); int main(int argc, char **argv) { pthread_t thr; int a = 10; if(pthread_create(&thr, NULL, &print_hello, (void *)&a)) { printf("Could not create thread\n"); return -1; } .... return 0; } void * print_hello(void *arg) { int a = (int)*arg; printf("Hello world and %d!\n", a); return NULL; }