質問:
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) に提供した値) を、戻ります。」
これを示すこのコードを書きました。コードのコメントを参照してください。
#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:
私はスレッドにいます。
引数アドレスは 0xbfa64878 0xbfa64878 です
返されるステータスのアドレスは 0xbfa64878、返されるステータスは 991***