发布时间:2025-12-09 11:59:47 浏览次数:2
查阅了相关资料,调用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函数后,整个程序全部退出了,包括子线程。