1. 程式人生 > >多執行緒情況下,主執行緒先退出,子執行緒會被強制退出嗎

多執行緒情況下,主執行緒先退出,子執行緒會被強制退出嗎

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()無法執行了,

所以要到其他執行緒全部執行完了,整個程序才會退出。