它抱怨线程函数(绑定到的pthread_create
第三个参数),你可以修改采取void *
参数,然后用它做任何事情之前将它转换回:
void *start (void *voidData) {
threadData *data = voidData;
// rest of code here, using correctly typed data.
你可能也选择将数据指针(第四个参数)强制到预期的类型:
(void*)(&(data[id]))
,但我不认为这是必要的,因为一个void *
为s无法自由兑换大多数其他指针。
你可以看到这个问题在这个小而完整的程序:
#include <stdio.h>
#include <string.h>
#include <pthread.h>
struct sData { char text[100]; };
void *start (struct sData *data) {
printf ("[%s]\n", data->text);
}
int main (void) {
struct sData sd;
pthread_t tid;
int rc;
strcpy (sd.text, "paxdiablo");
rc = pthread_create (&tid, NULL, start, &sd);
pthread_join (tid, NULL);
return 0;
}
,在编译,你会看到:
prog.c: In function 'main':
prog.c:20:2: warning: passing argument 3 of 'pthread_create' from
incompatible pointer type [enabled by default]
In file included from prog.c:3:0:
/usr/include/pthread.h:225:12: note: expected
'void * (*)(void *)' but argument is of type
'void * (*)(struct sData *)'
请记住,这只是一个警告,不是一个错误,但是,如果你想让你的代码干净地编译,那么值得摆脱。在制作这个答案(巴数据参数铸造)的顶部提到的更改为您提供了以下线程函数:
void *start (void *voidData) {
struct sData *data = voidData;
printf ("[%s]\n", data->text);
}
这编译没有警告,并运行良好。
第一个答案解释了如何解决您的问题。 – 2501 2014-12-04 03:10:57