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 bugs
9 Warning
10 */
11
Namespace Sidle
13 {
The using namespace System;
using namespace system::threading;
16
Template
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