Listing 6: The final solution a singleton that uses the Double-Checked Locking Pattern
// solution.h #include "sync.h" class Singleton { public: static Singleton& instance(); void show_state(); protected: Singleton(); private: static Singleton* _instance; static Critical_Section _key; int state; }; Singleton* Singleton::_instance = NULL; Critical_Section Singleton::_key; Singleton& Singleton::instance() { if(!_instance) // Lock-hint check (Race condition here) { Lock_Guard<Critical_Section> gate(_key); if(!_instance) // Double-check (Race condition resolved) _instance = new Singleton; } return *_instance; }