<分区>
考虑这个简单的代码:
void* threadFunction(void* arg) {
int argument=(int)arg;
printf("%d recieved\n", argument);
return NULL;
}
int main(int argv, char* argc[]) {
int error;
int i=0;
pthread_t thread;
int argument_to_thread=0;
if ((error=pthread_create(&thread, NULL, threadFunction, (void*)argument_to_thread))!=0) {
printf("Can't create thread: [%s]\n", strerror(error));
return 1;
}
pthread_join(thread, NULL);
return 0;
}
这行得通,但有两件事困扰着我。
首先,我想向 threadFunction() 发送多个参数。
当然,我可以传递一个指向数组的指针,但是如果我想传递两个不同类型的参数呢? (比如 int
和 char*
)如何实现?
这里困扰我的第二件事是编译上述内容时收到的警告...
test2.c: In function ‘threadFunction’:
test2.c:8:15: warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]
int argument=(int)arg;
^
test2.c: In function ‘main’:
test2.c:24:59: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
if ((error=pthread_create(&thread, NULL, threadFunction, (void*)argument_to_thread))!=0) {
^
现在,我可以通过这样做来解决这个问题:
if ((error=pthread_create(&thread, NULL, threadFunction, (void*)&argument_to_thread))!=0) {
printf("Can't create thread: [%s]\n", strerror(error));
return 1;
}
但是假设我不想通过引用传递它...有没有办法在编译器不警告我的情况下通过值作为参数传递,比如说...一个 int?