看板 LinuxDev 關於我們 聯絡資訊
我程式碼中把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 影響到提早結束 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 175.182.113.117 ※ 文章網址: https://www.ptt.cc/bbs/LinuxDev/M.1543068296.A.7DE.html
liang168: 這沒你講的那麼複雜 但真的有興趣看看 恐龍書吧 11/24 22:35
※ 編輯: shihyu (175.182.113.117), 11/24/2018 23:39:50
b0920075: fork是直接跑一個process出來,跟用同個process搞threa 11/25 14:51
b0920075: d出來差很多吧 11/25 14:51
tjjh89017: 我覺得這部分的情況可能會是child先死,導致的zombie 11/25 15:02
tjjh89017: process,所以init才不會去接管 11/25 15:02
tjjh89017: 或者是因為parent process結束,fd 0,1被導回bash 11/25 15:03
tjjh89017: 所以child process print不會顯示 11/25 15:03
yvb: https://goo.gl/pvfkby 11/25 17:56
yvb: 在程式 pthread_join() 下加一行 pthread_exit(&ret); 試試. 11/25 17:58
yvb: 搭配 ps ax 和 ps axH 看看 process 和 threads 的情況. 11/25 17:59
kingofsdtw: https://linux.die.net/man/3/pthread_join 11/26 19:26
kingofsdtw: http://bfy.tw/L2XF 11/26 19:28
shihyu: yvb 感謝喔 11/27 21:58
※ 編輯: shihyu (106.104.69.161), 11/27/2018 21:58:56