Double checked locking pattern was used in sigleton initialization in multi-threaded environments prior to C++11.
Singleton* Singleton::getInstance() {
Singleton* tmp = m_instance.load(std::memory_order_acquire);
if (tmp == nullptr) {
std::lock_guard lock(m_mutex);
tmp = m_instance.load(std::memory_order_relaxed);
if (tmp == nullptr) {
tmp = new Singleton;
m_instance.store(tmp, std::memory_order_release);
}
}
return tmp;
}
C++11 removes the need for manual locking. It guarantees concurrent execution shall wait if a static local variable is already being initialized. You can simply use a static initializer.
Singleton& Singleton::getInstance() {
static Singleton instance;
return instance;
}