1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| class Singleton { public: static Singleton* GetInstance(); static Singleton* m_Instance; private: Singleton(); Singleton( const Singleton& singleton ); };
Singleton* Singleton::GetInstance(){ if ( m_Instance != nullptr ) return m_Instance; m_Instance = new Singleton(); }
Singleton* Singleton::GetInstance(){ Lock lock; ... }
Singleton* Singleton::GetInstance(){ if ( m_Instance != nullptr ) return m_Instance; Lock lock; if ( m_Instance != nullptr ) return m_Instance; m_Instance = new Singleton(); return m_Instance; }
std::atomic<Sigleton*> Singleton::m_Instance; std::mutex Singleton:m_Mutex;
Singleton* Singleton::GetInstance(){ singleton *tmp = m_Instance.load(memory_order_relaxed); std::atomic_thread_fence(std::memory_order_acquire); if ( tmp != nullptr ) return m_Instance; std::lock_guard<std::mutex> guard(m_Mutex); tmp = m_Instance.load(memory_order_relaxed); if ( m_Instance != nullptr ) return m_Instance; tmp = new Singleton(); atomic_thread_fence(memory_order_release); m_Instance.store(tmp, memory_order_relaxed); return m_Instance; }
|