gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 12:49:33 24 4
gpt4 key购买 nike

问题:

退出状态到底是如何在 pthread_exit 和 pthread_join 之间传递的?

来自pthread_join man page

   int pthread_join(pthread_t thread, void **retval);

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.

我认为手册页中的措辞不正确。

应该是“如果 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);
}

示例o/p:

我在线程中。

arg地址是0xbfa64878 0xbfa64878

返回状态地址为0xbfa64878,返回状态为991***

最佳答案

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

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.

您使用 retval=&status 调用 pthread_join,因此它不为 NULL。

您调用了pthread_exit(0xbfa64878),因此目标线程的退出状态为0xbfa64878,并且该状态被复制到*retval中,即status = 0xbfa64878,这是您打印出来的内容。

我认为您将标签与“返回状态的地址”和“arg 地址”等标签混淆了......您为 pthreads 未暗示的值赋予了标签。手册页所说的是,*retval 设置为传递给 pthread_exit 的值,这就是您的测试显示的内容。

在您提议的更改中:

If retval is not NULL, then pthread_join() copies the address of the variable holding 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.

什么是“保存目标线程退出状态的变量”? Pthreads 没有定义这样的东西。目标线程的退出状态是传递给pthread_exit的值,而不是其他变量的值。

关于c - 退出状态如何在 pthread_exit 和 pthread_join 之间传递?手册页中是否需要更正?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16629645/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com