2013-05-18 27 views
1

問題:pthread_exit和pthread_join之間的退出狀態是如何傳遞的?手冊頁需要更正嗎?

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); 
} 

樣品O/P:

我在線程。

的ARG地址是0xbfa64878 0xbfa64878

的返回狀態的地址是0xbfa64878,返回的狀態是991 ***

+0

...和你的問題是什麼? – stakx

+2

退出狀態*是*空指針。它不是*(必然)是任何東西的地址。 –

+0

@stakx我添加了一個問題。我認爲我的問題是隱含的,但現在我添加了一個明確的問題。感謝您指出了這一點。 – abc

回答

5

您的代碼並不矛盾手冊頁。

如果RETVAL不是NULL,則在pthread_join()拷貝目標線程的退出狀態(即,提供給了pthread_exit目標線程(3)的值)到位置由* RETVAL指向。

您致電pthread_joinretval=&status,所以它不是NULL。

你叫pthread_exit(0xbfa64878)所以目標線程的退出狀態是0xbfa64878和被複制到*retvalstatus = 0xbfa64878,這是你打印出來的東西。

我認爲你很容易混淆標籤,比如「返回狀態的地址」和「參數地址」......你給標籤賦予pthreads並不意味着的值。手冊頁說的是,*retval設置爲傳遞到pthread_exit的值,這就是您的測試顯示的內容。

在您建議的更改:

如果RETVAL不爲空,然後在pthread_join()將變量持有目標線程的退出狀態的地址(即,目標線程提供給pthread_exit(3)的值)放入retval指向的位置。

什麼是「保存目標線程退出狀態的變量」? Pthreads沒有定義這樣的事情。目標線程的退出狀態是傳遞給pthread_exit的值,它不是其他某個變量的值。

+0

謝謝。實際上,目標線程的退出狀態是傳遞給pthread_exit的值,它不是某個其他變量的值。我在考慮退出狀態必須是int值,並且不能是地址。但那不對。正確? – abc

+1

等一下,還是有問題。 「放入* retval指向的位置。」意味着* retval有一個地址,退出狀態被複製爲該地址的值。但是,發生的情況是退出狀態被複制到* retval本身而不是* retval指向的位置。它應該說:「放入retval指向的位置。」因爲retval是一個void **並且退出狀態是void *。我相信這是對的。 – abc

+0

嘿喬恩你覺得我的評論就在這個評論之上嗎?請告訴我。 – abc