Singleton [Double-Checked Locling] 双重加琐优化

Double-Checked Locking 实现:

同步类:

synobj.h

 1  #ifndef SYNOBJ_H
 2  #define SYNOBJ_H
 3  

 4  #include <windows.h>
 5  
 6  #define CLASS_UNCOPYABLE(classname) /
 7       private : /
 8      classname##( const  classname##&); /
 9      classname##& operator=( const  classname##&);
10  

11  class  Mutex {
12      CLASS_UNCOPYABLE(Mutex)
13  public :
14      Mutex() :_cs() { InitializeCriticalSection(&_cs); }
15      ~Mutex() { DeleteCriticalSection(&_cs); }
16       void  lock() { EnterCriticalSection(&_cs); }
17       void  unlock() { LeaveCriticalSection(&_cs); }
18  private :
19      CRITICAL_SECTION _cs;
20  };
21  

22  class  Lock {
23      CLASS_UNCOPYABLE(Lock)
24  public :
25      explicit Lock(Mutex& cs) :_cs(cs) { _cs.lock(); }
26      ~Lock() { _cs.unlock(); }
27  private :
28      Mutex& _cs;
29  };
30  

31  #endif /*SYNOBJ_H*/

 

有了同步对象很容易就能够写出如下代码:
singleton.h

1  #ifndef SINGLETON_H
 2  #define SINGLETON_H
 3  

 4  #include "synobj.h"
 5  
 6  class  Singleton {
 7  public :
 8       static  Singleton& Instance() {  // Unique point of access

If ( 0 == _instance)

{ // 因为 lock 只对 0 == _instance true 才有效,所以为了优化就再加入了一个判断。
 9                Lock lock(_mutex);
10                if  (0 == _instance) {
11                      _instance =  new  Singleton();
12                      atexit(Destroy);  // Register Destroy function

13                    }

}
14           return  *_instance;
15      }
16       void  DoSomething(){}
17  private :
18       static   void  Destroy() {  // Destroy the only instance

19           if  ( _instance != 0 ) {
20              delete _instance;
21              _instance = 0;
22          }
23      }
24      Singleton(){}  // Prevent clients from creating a new Singleton

25      ~Singleton(){}  // Prevent clients from deleting a Singleton
26      Singleton( const  Singleton&);  // Prevent clients from copying a Singleton
27      Singleton& operator=( const  Singleton&);
28  private :
29       static  Mutex _mutex;
30       static  Singleton  volatile *_instance;  // The one and only instance

// 为了防止编译器优化加入 volatile 这个修饰关键字
31  };
32  

33  #endif /*SINGLETON_H*/

singleton.cpp

1  #include "singleton.h"
2  
3  Mutex Singleton::_mutex;
4  Singleton*  volatile Singleton::_instance = 0; //
为了防止编译器优化加入 volatile 这个修饰关键字

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值