C++11:提高性能及操作硬件的能力(二)

2014-11-24 07:18:52 · 作者: · 浏览: 2
ucer() { string* p = new string("Hello"); data.store(42, memory_order_relaxed); ptr.store(p, memory_order_release); } void Consumer() { string* p2; while (!(p2 = ptr.load(memory_order_consume)))//#1#所有关于后序关于ptr的操作都必须在本原子操作之后 ; assert(*p2 == "Hello"); // 总是相等 assert(data.load(memory_order_relaxed) == 42); // 可能断言失败,因为#1#处只保证了ptr的顺序,而data.load可能先于ptr.load } int main() { thread t1(Producer); thread t2(Consumer); t1.join(); t2.join(); }

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 
  
   
#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); }
   
  
但是exit执行析构可能耗时,因此C++11引入了quick_exit,该函数不执行析构只是使程序终止。如:

#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); }