1 class Singleton{ 2 private: 3 Singleton(); 4 Singleton(const Singleton& other); 5 public: 6 static Singleton* getInstance(); 7 static Singleton* m_instance; 8 }; 9 10 Singleton* Singleton::m_instance=nullptr; 11 12 //线程非安全版本 13 Singleton* Singleton::getInstance() { 14 if (m_instance == nullptr) { 15 m_instance = new Singleton(); 16 } 17 return m_instance; 18 } 19 20 //线程安全版本,但锁的代价过高 21 Singleton* Singleton::getInstance() { 22 Lock lock; 23 if (m_instance == nullptr) { 24 m_instance = new Singleton(); 25 } 26 return m_instance; 27 } 28 29 //双检查锁,但由于内存读写reorder不安全 30 Singleton* Singleton::getInstance() { 31 32 if(m_instance==nullptr){ 33 Lock lock; 34 if (m_instance == nullptr) { 35 m_instance = new Singleton(); 36 } 37 } 38 return m_instance; 39 } 40 41 //C++ 11版本之后的跨平台实现 (volatile) 42 std::atomic<Singleton*> Singleton::m_instance; 43 std::mutex Singleton::m_mutex; 44 45 Singleton* Singleton::getInstance() { 46 Singleton* tmp = m_instance.load(std::memory_order_relaxed); 47 std::atomic_thread_fence(std::memory_order_acquire);//获取内存fence 48 if (tmp == nullptr) { 49 std::lock_guard<std::mutex> lock(m_mutex); 50 tmp = m_instance.load(std::memory_order_relaxed); 51 if (tmp == nullptr) { 52 tmp = new Singleton; 53 std::atomic_thread_fence(std::memory_order_release);//释放内存fence 54 m_instance.store(tmp, std::memory_order_relaxed); 55 } 56 } 57 return tmp; 58 }
原文:https://www.cnblogs.com/cxc1357/p/12310649.html