Created
December 24, 2013 11:51
-
-
Save jtsagata/8112218 to your computer and use it in GitHub Desktop.
Singleton notes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // http://en.wikipedia.org/wiki/Double-checked_locking | |
| Singleton& Singleton::getInstance() { | |
| static Singleton instance; | |
| return instance; | |
| } | |
| // More info | |
| // http://preshing.com/20130930/double-checked-locking-is-fixed-in-cpp11/ | |
| std::atomic<Singleton*> Singleton::m_instance; | |
| std::mutex Singleton::m_mutex; | |
| Singleton* Singleton::getInstance() { | |
| Singleton* tmp = m_instance.load(std::memory_order_relaxed); | |
| std::atomic_thread_fence(std::memory_order_acquire); | |
| if (tmp == nullptr) { | |
| std::lock_guard<std::mutex> lock(m_mutex); | |
| tmp = m_instance.load(std::memory_order_relaxed); | |
| if (tmp == nullptr) { | |
| tmp = new Singleton; | |
| std::atomic_thread_fence(std::memory_order_release); | |
| m_instance.store(tmp, std::memory_order_relaxed); | |
| } | |
| } | |
| return tmp; | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment