The singleton mode implemented by double detection lock (double-checked locking) has considerable value in multithreading application. The Ace_singleton template class is used extensively in the implementation of Aces to convert generic classes into classes with singleton behavior. This is a good way to eliminate some of the repeated code odor, and the optimized performance is 15 times times higher than the standard mutex version. Recently in the use of C++/CLI to do some work, singleton inevitably need to use, so I made another wheel.
1 #pragma once 2 3/** \class Sidle::singleton 4 \brief Singleton (double-checked locking) 5 \author Wulping 6 \version 1.0 7 \date 2005.02.08- 8 \bug 9 \warning 10 */ 11 Namespace Sidle 13 { The using namespace System; using namespace system::threading; 16 Template<typename _t> Ref class Singleton 19 { Public: Static _t^ Instance () 22 { if (_instance = = nullptr) 24 { _mut->waitone (); A try 27 { if (_instance = = nullptr) 29 { _instance = gcnew _t (); 31} 32} Finally 34 { _mut->releasemutex (); 36} 37} return _instance; 39} Protected: Singleton () {} The static _t^ _instance; The static mutex^ _mut = Gcnew Mutex (); 44}; Ref class Singleton 45 46}; Namespace Sidle |