2015-10-02 16 views
1
#include "iostream" 
#include "atomic" 

using namespace std; 

class Singleton 
{ 
    Singleton(); 


    static Singleton * _pInstance; 

    public: 
     ~Singleton() { 
     } 

     static Singleton* getInstance() { 

      Singleton * tmp = _pInstance; 

      atomic_thread_fence(std::memory_order_acquire); 

      if (tmp == nullptr){ 

      tmp = _pInstance; 

      if (!tmp) { 

       _pInstance = new Singleton(); 

       atomic_thread_fence(std::memory_order_release); 

       _pInstance = tmp; 
      } 

     return _pInstance; 
    } 
}; 

Singleton* Singleton::_pInstance = nullptr; 
+0

你能详细说明你的问题吗? – Raptor

+2

我不知道这个,但它实现一个线程安全的单例是*微不足道的*。最简单的单身人士,一个迈耶斯的单身人士,已经是线程安全的。 –

+0

双重检查锁定模式的危险:http://www.aristeia.com/Papers/DDJ_Jul_Aug_2004_revised.pdf –

回答

3

你的执行似乎是线程安全的,但最简单的方法,使一个线程安全的单看起来像

class Singleton { 
    Singleton(); 

public: 
    ~Singleton() { 
    } 

    static Singleton* getInstance() { 
     static Singleton theInstance; 
     return &theInstance; 
    } 
}; 

或更好返回参考

static Singleton& getInstance() { 
     static Singleton theInstance; 
     return theInstance; 
    } 

你不需要在这里重新发明轮子。

相关问题