首页 文章

如何在pthread_exit和pthread_join之间传递退出状态?是否需要在手册页中进行更正?

提问于
浏览
1

题:

pthread_exit和pthread_join之间的退出状态究竟是如何传递的?

pthread_join man page

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 回答

  • 5

    您的代码与手册页不矛盾 .

    如果retval不为NULL,则pthread_join()将目标线程的退出状态(即目标线程提供给pthread_exit(3)的值)复制到* retval指向的位置 .

    你用 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 的值,这就是您的测试显示的内容 .

    在您提议的更改中:

    如果retval不为NULL,则pthread_join()将保存目标线程的退出状态的变量的地址(即,目标线程提供给pthread_exit(3)的值)复制到retval指向的位置 .

    什么是"the variable holding the exit status of the target thread"? Pthreads没有定义这样的东西 . 目标线程 is the value passed to pthread_exit 的退出状态,它不是某个其他变量的值 .

相关问题