1、进程中线程之间的关系
线程不像进程,一个进程中的线程之间是没有父子之分的,都是平级关系。即线程都是一样的, 退出了一个不会影响另外一个。
但是所谓的"主线程"main,其入口代码是类似这样的方式调用main的:exit(main(...))。
main执行完之后, 会调用exit()。
exit() 会让整个进程over终止,那所有线程自然都会退出。
2、主线程先退出,子线程继续运行的方法
在进程主函数(main())中调用pthread_exit(),只会使主函数所在的线程(可以说是进程的主线程)退出;而如果是return,编译器将使其调用进程退出的代码(如_exit()),从而导致进程及其所有线程结束运行。
理论上说,pthread_exit()和线程宿体函数退出的功能是相同的,函数结束时会在内部自动调用pthread_exit()来清理线程相关的资源。但实际上二者由于编译器的处理有很大的不同。
按照POSIX标准定义,当主线程在子线程终止之前调用pthread_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.
main()中调用了pthread_exit后,导致住线程提前退出,其后的exit()无法执行了,所以要到其他线程全部执行完了,整个进程才会退出。