博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

主线程 子线程 退出

Posted on 2016-06-15 12:15  bw_0927  阅读(477)  评论(0)    收藏  举报

理论上说,pthread_exit()和线程宿体函数退出的功能是相同的,函数结束时会在内部自动调用pthread_exit()来清理线程相关的资源。但实际上二者由于编译器的处理有很大的不同。
在进程主函数(main())中调用pthread_exit(),只会使主函数所在的线程(可以说是进程的主线程)退出;而如果是return,编译器将使其调用进程退出的代码(如_exit()),从而导致进程及其所有线程结束运行。

 

When you program with POSIX Threads API, there is one thing about pthread_exit() that you may ignore for mistake. In subroutines that complete normally, there is nothing special you have to do unless you want to pass a return code back using pthread_exit(). The completion won't affect the other threads which were created by the main thread of this subroutine. 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 that main() created before, you can dispense with calling any functions. But if you want to keep the process and all the other threads except 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 open after its termination.
按照POSIX标准定义,当主线程在子线程终止之前调用pthread_exit()时,子线程是不会退出的
 
 

这个其实很简单,因为调用exit会使整个进程终止,而在main中return实际上就会调用到exit而导致所有线程都终止。入口代码是类似这样的方式调用main的:
exit(main(...));