C,C++函数exit用来终止当前程序, 函数定义如下:
void exit (int status);
官方说明如下:
Terminates the process normally, performing the regular cleanup for terminating programs.
Normal program termination performs the following (in the same order):
第一点:
这里的thread storage指的是线程局部存储, 在线程作用域有效, c++11定义thread storage如下:
thread_local Object obj; //Object为C++类
thread_local int value = 1;
Object gObj;
void fun(){
static Object sObj;
}
int atexit (void (*func)(void));
/* atexit example */
#include /* puts */
#include /* atexit */
void fnExit1 (void)
{
puts ("Exit function 1.");
}
void fnExit2 (void)
{
puts ("Exit function 2.");
}
int main ()
{
atexit (fnExit1);
atexit (fnExit2);
puts ("Main function.");
exit(0);
}
Main function.
Exit function 2.
Exit function 1.
#include
#include
#include
#include
#include
#include
class MyObject
{
public:
std::string str;
public:
MyObject(std::string str){
this->str = str;
}
~MyObject(){
printf("%s -- %s\n", __FUNCTION__, str.c_str());
}
};
void thread_fun(int n)
{
thread_local MyObject threadObj("thread_local subthread obj");
//do something
sleep(2);
}
void exit_fun(){
MyObject threadObj("atexit obj");
//do something
sleep(1);
}
MyObject obj("global obj");
int main(int argc, const char * argv[])
{
thread_local MyObject threadObj("thread_local mainthread obj");
static MyObject staticObj("fun static obj");
std::thread t(thread_fun, 1);
atexit(exit_fun);
sleep(2);
exit(0);
}
~MyObject -- thread_local subthread obj
~MyObject -- thread_local mainthread obj
~MyObject -- atexit obj
~MyObject -- fun static obj
~MyObject -- global obj
Program ended with exit code: 0
void abort (void);
MyObject gObj("global obj");
// ------>
MyObject* pObj = new MyObject("global obj ptr");