Skip to content

Instantly share code, notes, and snippets.

@jtsagata
Created December 24, 2013 11:51
Show Gist options
  • Select an option

  • Save jtsagata/8112218 to your computer and use it in GitHub Desktop.

Select an option

Save jtsagata/8112218 to your computer and use it in GitHub Desktop.
Singleton notes
// 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