Double-Checked Locking 实现:
同步类:
synobj.h
1
#ifndef SYNOBJ_H
2
#define SYNOBJ_H
3
4
#include <windows.h>
5
6
#define CLASS_UNCOPYABLE(classname) /
7
private
: /
8
classname##(
const
classname##&); /
9
classname##& operator=(
const
classname##&);
10
11
class
Mutex {
12
CLASS_UNCOPYABLE(Mutex)
13
public
:
14
Mutex() :_cs() { InitializeCriticalSection(&_cs); }
15
~Mutex() { DeleteCriticalSection(&_cs); }
16
void
lock() { EnterCriticalSection(&_cs); }
17
void
unlock() { LeaveCriticalSection(&_cs); }
18
private
:
19
CRITICAL_SECTION _cs;
20
};
21
22
class
Lock {
23
CLASS_UNCOPYABLE(Lock)
24
public
:
25
explicit Lock(Mutex& cs) :_cs(cs) { _cs.lock(); }
26
~Lock() { _cs.unlock(); }
27
private
:
28
Mutex& _cs;
29
};
30
31
#endif
/*SYNOBJ_H*/
有了同步对象很容易就能够写出如下代码:
singleton.h
1
#ifndef SINGLETON_H
2
#define SINGLETON_H
3
4
#include "synobj.h"
5
6
class
Singleton {
7
public
:
8
static
Singleton& Instance() {
// Unique point of access
If ( 0 == _instance)
{ //
因为
lock
只对
0 == _instance
为
true
才有效,所以为了优化就再加入了一个判断。
9
Lock lock(_mutex);
10
if
(0 == _instance) {
11
_instance =
new
Singleton();
12
atexit(Destroy);
// Register Destroy function
13
}
}
14
return
*_instance;
15
}
16
void
DoSomething(){}
17
private
:
18
static
void
Destroy() {
// Destroy the only instance
19
if
( _instance != 0 ) {
20
delete _instance;
21
_instance = 0;
22
}
23
}
24
Singleton(){}
// Prevent clients from creating a new Singleton
25
~Singleton(){}
// Prevent clients from deleting a Singleton
26
Singleton(
const
Singleton&);
// Prevent clients from copying a Singleton
27
Singleton& operator=(
const
Singleton&);
28
private
:
29
static
Mutex _mutex;
30
static
Singleton
volatile
*_instance;
// The one and only instance
//
为了防止编译器优化加入
volatile
这个修饰关键字
31
};
32
33
#endif
/*SINGLETON_H*/
singleton.cpp
1
#include "singleton.h"
2
3
Mutex Singleton::_mutex;
4
Singleton*
volatile
Singleton::_instance = 0;
//
为了防止编译器优化加入
volatile
这个修饰关键字