4 线程私有数据
在POSIX中在变量前加一个__thread就声明该变量为线程私有数据,
基本类型(如(unsigned) int,long, char,指针,c类型的结构体等 )可以采用用 __thread修饰符来定义线程局部变量.
示例如下:
__thread int i; extern __thread struct state s; static __thread char *p;
像 string 等类是不能直接用 __thread 修符的,只能用其指针类型的.如下面的示例是错误的.
thread std::string thread_name;
下面是正确的:
thread std::string * p_thread_name;
使用 __thread修饰符来定义一些类的线程局部变量,往往容易造成内存泄漏.
5 线程退出方式
teminate终止进程,它调用底层的abort,它们不会调用任何析构函数,向系统发送一个SIGABRT信号,若程序员定义了该信号的信号处理程序清理资源的话操作系统会释放资源。它们属于异常退出。
exit和main中的return一样是正常退出,会执行析构操作,如果注册了处理函数则还会执行清理函数。如:
#include但是exit执行析构可能耗时,因此C++11引入了quick_exit,该函数不执行析构只是使程序终止。如:#include using namespace std; void openDevice() { cout << "device is opened." << endl; } void resetDeviceStat() { cout << "device stat is reset." << endl; } void closeDevice() { cout << "device is closed." << endl; } int main() { atexit(closeDevice); atexit(resetDeviceStat);//注册清理函数,清理函数的执行和注册时的顺序相反 openDevice(); exit(0); }
#include#include using namespace std; struct A { ~A() { cout << "Destruct A. " << endl; } }; void closeDevice() { cout << "device is closed." << endl; } int main() { A a; at_quick_exit(closeDevice);//与quick_exit配套的清除函数的注册 quick_exit(0); }