C 使用pthread_exit()返回retval时出现编译警告
我有以下资料:C 使用pthread_exit()返回retval时出现编译警告,c,linux,pthreads,C,Linux,Pthreads,我有以下资料: 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 **)&
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\u exit()
我根本找不到问题所在:(…而不是这个:
pthread_exit((void *)ret);
写下:
pthread_exit((void *)&ret);
在“pthread_exit((void*)ret)”中,您告诉pthread_exit
在地址处有一个返回值,与ret变量中包含的值有关。您希望结果存储在ret的地址,因此它应该是pthread_exit(&ret)
现在,ret
是一个局部整数变量。如果您编写:
int *ret=malloc(sizeof(int));
if(ret==NULL)
//handle the error
*ret=func();
pthread_exit(ret);
不要忘记释放指针。您正在将非指针投射到指针-这可能就是您收到警告的原因。
也许您可以修改代码,使用int*
而不是int-ret
,并将其转换为void*
编辑:正如Tony The Lion提到的。因此,您试图从线程函数返回一个整数值。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);
现在返回一个局部变量的地址。而作者希望返回值。这很危险。:)但我只是在修正警告信息。关注这个问题。但是,是的,我也会编辑它来反映这一点。好吧,这样的修正改变了行为,不再有用了。你怎么会找不到问题所在呢。编译器告诉您:“从不同大小的整数转换为指针”。什么东西这么难理解?