查閱了相關資料,呼叫exit函式會直接將行程回傳給作業系統,不論是在行程中主執行緒還是子執行緒中呼叫,都會直接將控制權回傳給作業系統,

代碼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);
}
輸出如下:

代碼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函式后,整個程式全部退出了,包括子執行緒,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/27287.html
標籤:C
上一篇:佇列-鏈式存盤
下一篇:手把手教系列之移動平均濾波器實作
