题:
pthread_exit和pthread_join之间的退出状态究竟是如何传递的?
int pthread_join(pthread_t thread, void **retval);
如果retval不为NULL,则pthread_join()将目标线程的退出状态(即目标线程提供给pthread_exit(3)的值)复制到* retval指向的位置 . 如果目标线程被取消,则PTHREAD_CANCELED被置于* retval中 .
我认为手册页中的措辞不正确 .
它应该是“如果retval不为NULL,则pthread_join()将保存目标线程的退出状态的变量的地址(即,目标线程提供给pthread_exit(3)的值)复制到指向的位置 . RETVAL“ .
我写了这段代码,显示了这一点,请参阅代码注释:
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
void * function(void*);
int main()
{
pthread_t thread;
int arg = 991;
int * status; // notice I did not intialize status, status is *retval
pthread_create(&thread, NULL, function, (void*)(&arg));
pthread_join(thread, (void **)(&status));//passing address of status,&status is retval
//(2) this address is same as printed in (1)
printf("The address of returned status is %p,", status);
printf("The returned status is %d\n", *status);
}
void * function(void * arg)
{
int *p;
p = (int*)arg;
printf("I am in thread.\n");
//(1) printing the address of variable holding the exit status of thread, see (2)
printf("The arg address is %p %p\n", p, arg);
pthread_exit(arg);
}
Sample o/p:
我在线程中 .
arg地址为0xbfa64878 0xbfa64878
返回状态的地址为0xbfa64878,返回状态为991 ***
1 回答
您的代码与手册页不矛盾 .
你用
retval=&status
调用pthread_join
,所以它不是NULL .您调用
pthread_exit(0xbfa64878)
,因此目标线程的退出状态为0xbfa64878
,并将其复制到*retval
,即status = 0xbfa64878
,这是您打印出来的内容 .我认为你给了pthreads并不意味着的值的标签're confusing things with labels such as 3016223 and 3016224 ... you' . 该手册页所说的是
*retval
被设置为传递给pthread_exit
的值,这就是您的测试显示的内容 .在您提议的更改中:
什么是"the variable holding the exit status of the target thread"? Pthreads没有定义这样的东西 . 目标线程 is the value passed to pthread_exit 的退出状态,它不是某个其他变量的值 .