Ank*_*wal 2 c multithreading pthreads
题:
pthread_exit和pthread_join之间的退出状态究竟是如何传递的?
int pthread_join(pthread_t thread, void **retval);
Run Code Online (Sandbox Code Playgroud)
如果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);
}
Run Code Online (Sandbox Code Playgroud)
样本o/p:
我在线程中.
arg地址为0xbfa64878 0xbfa64878
返回状态的地址为0xbfa64878,返回状态为991***
您的代码与手册页不矛盾.
如果retval不为NULL,则pthread_join()将目标线程的退出状态(即目标线程提供给pthread_exit(3)的值)复制到*retval指向的位置.
你打电话pthread_join给retval=&status,所以它不是NULL.
您调用pthread_exit(0xbfa64878)了目标线程的退出状态,0xbfa64878并将其复制到*retvalie status = 0xbfa64878,即打印出来的内容.
我认为你的标签很混乱,比如"返回状态的地址"和"arg地址"......你给pthreads并不暗示的值赋予了标签.手册页所说的是*retval设置为传递给的值pthread_exit,这就是测试显示的内容.
在您提议的更改中:
如果retval不为NULL,则pthread_join()将保存目标线程的退出状态的变量的地址(即,目标线程提供给pthread_exit(3)的值)复制到retval指向的位置.
什么是"保持目标线程退出状态的变量"?Pthreads没有定义这样的东西.目标线程的退出状态是传递给的值pthread_exit,它不是某个其他变量的值.
| 归档时间: |
|
| 查看次数: |
4199 次 |
| 最近记录: |