[问题] 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