加入收藏 | 设为首页 | 会员中心 | 我要投稿 济南站长网 (https://www.0531zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 服务器 > 搭建环境 > Unix > 正文

UNIX环境高级编程:主线程与子线程的退出关系

发布时间:2016-10-03 06:35:45 所属栏目:Unix 来源:站长网
导读:副标题#e# 我们在一个线程中经常会创建另外的新线程,如果主线程退出,会不会影响它所创建的新线程呢?下面就来讨论一下。 1、 主线程等待新线程先结束退出,主线程后退出。正常执行。 示例代码: #include stdio.h #include stdlib.h #include pthread.h #

运行结果:

huangcheng@ubuntu:~$ ./a.out
main thread pid 2385 tid 3077768896 (0xb77306c0)  
new thread pid 2385 tid 3077766000 (0xb772fb70)

POSIX标准定义:

When you program with POSIX Threads API,there is one thing about pthread_exit() that you may ignore for mistake. Insubroutines that complete normally, there is nothing special you have to dounless you want to pass a return code back using pthread_exit(). The completionwon't affect the other threads which were created by the main thread of thissubroutine. However, in main(), when the code has been executed to the end,there could leave a choice for you. If you want to kill all the threads thatmain() created before, you can dispense with calling any functions. But if you want to keep the process and all the other threadsexcept for the main thread alive after the exit of main(), then you can call pthread_exit()to realize it. And any files opened inside the main thread will remain openafter its termination.

按照POSIX标准定义,当主线程在子线程终止之前调用pthread_exit()时,子线程是不会退出的。

注意:这里在main函数中调用pthread_exit()只会是主线程退出,而进程并未退出。因此新线程继续执行而没有退出。

我们可以在return 0;这条语句前面添加一条输出语句printf(“Mainthread has exited!n”);来进行测试,输出结果不发生任何变化,说明这条语句没有被执行到。也就说明进程并未退出。

因此:

一个线程的退出不会影响另外一个线程。但是进程结束,所有线程也就结束了,所有资源会被回收。

我们可以再写一个程序来进行验证:

4、在创建的新线程B中再次创建新线程C,那么如果B先退出,那么C将会继续执行而不会退出。

(编辑:济南站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

推荐文章
    热点阅读