[問題] pthread_join 作用

作者: shihyu (shihyu)   2018-11-24 22:04:53
我程式碼中把pthread_join 註解test函數thread無法印完10次
但是我網路看到解釋 pthread_join 讓main thread 等待test函數的做完才能做資源釋放
為什麼 main thread 結束 也會影響 test函數的thread 也跟著結束?
而不是像 process 父行程先死掉變成孤兒的概念 由 init 行程去回收?
謝謝
#include <pthread.h>
void test(void)
{
int i;
for (i = 0; i < 10; i++) {
printf("This is a thread n\n");
}
}
int main(void)
{
pthread_t id;
int i, ret;
pthread_create(&id, NULL, (void*) test, NULL);
for (i = 0; i < 2; i++) {
printf("This is the process n");
}
// pthread_join(id, NULL);
return (0);
}
https://gist.github.com/shihyu/10f7021b4a0f277b1cf9d045a8d41e86
我不懂是 fork 的父行程先結束 , 子行程可以印完才結束,
但是子thread會被父thread 影響到提早結束
作者: liang168 (小強)   2018-11-24 22:35:00
這沒你講的那麼複雜 但真的有興趣看看 恐龍書吧
作者: b0920075 (Void)   2018-11-25 14:51:00
fork是直接跑一個process出來,跟用同個process搞thread出來差很多吧
作者: tjjh89017 (伊達政宗)   2018-11-25 15:02:00
我覺得這部分的情況可能會是child先死,導致的zombieprocess,所以init才不會去接管或者是因為parent process結束,fd 0,1被導回bash所以child process print不會顯示
作者: yvb   2018-11-25 17:56:00
https://goo.gl/pvfkby在程式 pthread_join() 下加一行 pthread_exit(&ret); 試試.搭配 ps ax 和 ps axH 看看 process 和 threads 的情況.
作者: kingofsdtw (不能閒下來!!)   2018-11-26 19:26:00
作者: shihyu (shihyu)   2018-11-27 21:58:00
yvb 感謝喔

Links booklink

Contact Us: admin [ a t ] ucptt.com