[英]Properties of pthread_exit function : which one is right?
在 CSAPP 書第 12.3 節中,他們說..
線程通過調用pthread_exit function顯式終止。 如果主線程調用pthread_exit ,它會等待所有其他對等線程終止,然后終止主線程和整個進程,返回值為 thread_return。
但是在pthread_exit的手冊頁中: https://man7.org/linux/man-pages/man3/pthread_exit.3.html
對除主線程之外的任何線程執行從開始 function 的返回會導致對 pthread_exit() 的隱式調用,使用函數的返回值作為線程的退出狀態。
為了允許其他線程繼續執行,主線程應該通過調用 pthread_exit() 而不是 exit(3) 來終止。
關於pthread_exit的兩個描述是不同的。 第一個說主線程將等待對等點,但不是第二個。
因此我編寫了一個代碼來確保正確的屬性。
(我借用了一些代碼行當主線程退出時,其他線程是否也退出? )
(感謝https://stackoverflow.com/users/959183/laifjei )
由於pthread_cancel在pthread_exit之前調用,主線程成功取消 t1 線程,結果如下,
但是,當我將代碼修改為 '42 line -> add //' 和 '44 line -> delete //' 時,主線程無法取消 t1,因為它已經終止。 因此,以下結果看起來像,,
最后,我得出結論,手冊頁的屬性是正確的。 我對嗎?
為什么CSAPP書說“它等待所有其他對等線程終止”?
關於 pthread_exit 的兩個描述是不同的。 第一個說主線程將等待對等點,但不是第二個。
沒有太大的不同,也不是您可以通過大多數方式輕松區分的方式。
特別是,無論主線程是立即終止還是等待其他線程終止后再執行, pthread_exit()
function 就像exit()
function 一樣,它不會返回。 觀察到在pthread_exit()
調用和main
結束之間插入到測試程序中的語句沒有被執行,確實會產生任何信息來幫助您確定線程終止的相對順序。
出於這個原因,這個問題在很大程度上也沒有實際意義。 雖然確實有一些方法可以觀察到差異,但它很少顯着。
不過,這里有一個更好的例子:
#include <stdio.h>
#include <errno.h>
#include <pthread.h>
pthread_t main_thread;
void *wait_for_main(void *unused) {
void *main_rval;
// Wait for the main thread to terminate
if ((errno = pthread_join(main_thread, &main_rval)) != 0) {
perror("pthread_join");
} else {
fputs("The main thread was successfully joined\n", stderr);
}
fflush(stderr);
return NULL;
}
int main(void) {
pthread_t child_thread;
main_thread = pthread_self();
if ((errno = pthread_create(&child_thread, NULL, wait_for_main, NULL)) != 0) {
perror("pthread_create");
} else {
fputs("The child thread was successfully started\n", stderr);
}
pthread_exit(NULL);
}
該程序運行成功,正在打印...
子線程啟動成功
主線程已成功加入
這表明主線程確實終止了(因為它已成功加入),並且另一個線程隨后繼續運行(因為它將其消息寫入stderr
)。
你go上去問...
為什么CSAPP書說“它等待所有其他對等線程終止”?
......但除了科比、奧哈拉隆或他們的一位編輯之外,沒有人能明確回答這個問題(也許不是全部——或任何——這些問題)。 以下是一些可能性:
或者我實際的最佳猜測:
pthread_exit()
終止。 那就是這本書在談論 pthread 實現細節,沒有記錄,可觀察的 pthread 語義。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.