helloworld:design_pattern:singleton:cplusplus
Ceci est une ancienne révision du document !
Consider again pInstance = new Singleton;, the line that initializes pInstance. This statement causes three things to happen:
Step 1. Allocate memory to hold a Singleton object. Step 2. Construct a Singleton object in the allocated memory. Step 3. Make pInstance point to the allocated memory.Of critical importance is the observation that compilers are not constrained to perform these steps in this order! In particular, compilers are sometimes allowed to swap Steps 2 and 3. Why they might want to do that is a question we'll address in a moment. For now, let's focus on what happens if they do. C++ and The Perils of Double-Checked Locking: Part I (Archive)
En gros, le pointeur peut être différent de null
mais pour autant l'objet peut ne pas avoir été construit si le thread est arrêté entre l'étape 2 et 3 et qu'elles sont inversées.
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; }
helloworld/design_pattern/singleton/cplusplus.1480801959.txt.gz · Dernière modification : 2016/12/03 22:52 de root