pthread_exit的返回值没有被pthread_join取到
pthread_exit的返回值没有被pthread_join取到
pthread_join的man说,它会拿到pthread_exit的返回值:
--------------------
if retval is not NULL, then pthread_join() copies the exit status of the target thread (i.e., the value that the target thread supplied to
pthread_exit(3)) into the location pointed to by *retval. If the target thread was canceled, then PTHREAD_CANCELED is placed in *retval.
--------------------
于是我写了个小程序来验证:
C/C++ code?#include <assert.h> #include <pthread.h> #include <unistd.h> #include <iostream> using namespace std; void* fun(void*) { cout << "fun" << endl; int i=20; pthread_exit(&i); } int main() { pthread_t pt; cout << "main" << endl; int ret=pthread_create(&pt,NULL,fun,NULL); assert(ret==0); int *pi;//pthread return? sleep(1); cout << "join" << endl; pthread_join(pt,(void**)&pi); // get from pthread_exit cout << "i=" << *pi << endl; return 0; }
运行结果是:
main
fun
join
i=32591
我期待的结果是pthread_create创建的子线程线程当中,整形数i=20返回给了主线程的pthread_exit。但是和我预想的不太一样。
这是为什么呢?
不要返回线程函数的本地堆栈变量。把i=20声明为全局变量就行了。