[問題] pthread_join 作用

看板LinuxDev作者 (shihyu)時間5年前 (2018/11/24 22:04), 5年前編輯推噓4(409)
留言13則, 6人參與, 5年前最新討論串1/1
我程式碼中把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

11/24 22:35, 5年前 , 1F
這沒你講的那麼複雜 但真的有興趣看看 恐龍書吧
11/24 22:35, 1F
※ 編輯: shihyu (175.182.113.117), 11/24/2018 23:39:50

11/25 14:51, 5年前 , 2F
fork是直接跑一個process出來,跟用同個process搞threa
11/25 14:51, 2F

11/25 14:51, 5年前 , 3F
d出來差很多吧
11/25 14:51, 3F

11/25 15:02, 5年前 , 4F
我覺得這部分的情況可能會是child先死,導致的zombie
11/25 15:02, 4F

11/25 15:02, 5年前 , 5F
process,所以init才不會去接管
11/25 15:02, 5F

11/25 15:03, 5年前 , 6F
或者是因為parent process結束,fd 0,1被導回bash
11/25 15:03, 6F

11/25 15:03, 5年前 , 7F
所以child process print不會顯示
11/25 15:03, 7F

11/25 17:56, 5年前 , 8F
11/25 17:56, 8F

11/25 17:58, 5年前 , 9F
在程式 pthread_join() 下加一行 pthread_exit(&ret); 試試.
11/25 17:58, 9F

11/25 17:59, 5年前 , 10F
搭配 ps ax 和 ps axH 看看 process 和 threads 的情況.
11/25 17:59, 10F

11/26 19:26, 5年前 , 11F

11/26 19:28, 5年前 , 12F
11/26 19:28, 12F

11/27 21:58, 5年前 , 13F
yvb 感謝喔
11/27 21:58, 13F
※ 編輯: shihyu (106.104.69.161), 11/27/2018 21:58:56
文章代碼(AID): #1R-Lg8VU (LinuxDev)
文章代碼(AID): #1R-Lg8VU (LinuxDev)