Listing 5: The singleton of try1.h (Listing 2) with a critical section added
// try3.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() { Lock_Guard<Critical_Section> gate(_key); if(!_instance) _instance = new Singleton; return *_instance; }