使用pthread_exit()返回retval时编译警告

我有以下几点:

void *Thrd(void *data) { int ret; ret = myfunc(); pthread_exit((void *)ret); } int main(int argc, char *argv[]) { int status; pthread_create(&Thread, NULL, Thrd, &data); pthread_join(txThread, (void **)&status); if (status) printf("*** thread failed with error %d\n", status); } 

它的工作原理,我可以阅读状态,但编译时收到以下警告:

 test.cpp: In function 'void* Thrd(void*)': test.cpp:468:26: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast] 

这是pthread_exit()的行

我根本无法find什么是错的:( …

所以,你试图从一个线程函数返回一个整数值。 一个POSIX线程函数只能返回void*

有几种方法可以从另一个线程返回一个值:

1)你可以将一个整数转换为void*并返回,只要void*的宽度足以保存该值而不被截断:

 void *Thrd(void *vdata) { int value = ...; void* thread_return_value = (void*)value; return thread_return_value; } // ... void* status; pthread_join(txThread, &status); int value = (int)status; 

2)将返回值的地址传递给线程函数,并使线程函数设置该值:

 struct Data { int return_value; }; void *Thrd(void *vdata) { // ... int value = ...; struct Data* data = vdata; data->return_value = value; return NULL; } // ... pthread_create(&Thread, NULL, Thrd, &data); pthread_join(txThread, NULL); int value = data->return_value; 

3)让线程分配返回值。 连接()的另一个线程需要读取该值并将其解除分配:

 void *Thrd(void *vdata) { // ... int* value = malloc(sizeof *value); *value = ...; return value; } // ... void* status; pthread_join(txThread, &status); int* value = status; // ... free(value); 

你正在投射一个非指针指针 – 这可能是你得到警告的原因。 也许你可以修改你的代码来使用int*而不是你的int ret ,并将其转换为void*

编辑:正如托尼狮子提到的。

而不是这个:

 pthread_exit((void *)ret); 

写这个:

 pthread_exit((void *)&ret); 

在“pthread_exit((void *)ret)”中,你告诉pthread_exitpertaining to the value contained in ret variable地址处有一个返回值。 你希望结果存储在ret的地址,所以它应该是pthread_exit(&ret)

现在ret是一个局部整数变量。 如果你写:

 int *ret=malloc(sizeof(int)); if(ret==NULL) //handle the error *ret=func(); pthread_exit(ret); 

不要忘记free指针。