查閱了相關資料,調用exit函數會直接將進程返回給操做系統,不管是在進程中主線程仍是子線程中調用,都會直接將控制權返回給操做系統。ios
代碼1:在主線程中調用exit退出。函數
#include <iostream> #include <thread> using namespace std; void thread_fun() { cout<<"thread_fun run"<<endl; //exit(0); } void atexit_fun1() { cout<<"atexit fun1 run"<<endl; } void atexit_fun2() { cout<<"atexit fun2 run"<<endl; } int main() { /* thread thread_obj(thread_fun); thread_obj.join(); */ thread thread_obj(thread_fun); thread_obj.join(); cout<<"main run"<<endl; atexit(atexit_fun1); atexit(atexit_fun2); exit(0); }
輸出以下:spa
代碼2:在子線程中調用exit函數操作系統
#include <iostream> #include <thread> using namespace std; void thread_fun() { cout<<"thread_fun run"<<endl; exit(0); } void atexit_fun1() { cout<<"atexit fun1 run"<<endl; } void atexit_fun2() { cout<<"atexit fun2 run"<<endl; } int main() { /* thread thread_obj(thread_fun); thread_obj.join(); */ thread thread_obj(thread_fun); thread_obj.join(); cout<<"main run"<<endl; atexit(atexit_fun1); atexit(atexit_fun2); exit(0); }
輸出以下:線程
可見在子線程中調用exit函數後,整個程序所有退出了,包括子線程。blog