]>
Commit | Line | Data |
---|---|---|
da32329d AM |
1 | #ifndef SINGLETON_H |
2 | #define SINGLETON_H | |
3 | ||
4 | #ifdef CPP11 | |
5 | #include <atomic> | |
6 | #include <mutex> | |
7 | ||
8 | ||
9 | template<class T> | |
10 | class Singleton { | |
11 | public: | |
12 | static T& instance() | |
13 | { | |
14 | T * tmp = instance_.load(std::memory_order_consume); | |
15 | if (!tmp) { | |
16 | std::lock_guard<std::mutex> guard(instantiation_mutex); | |
17 | tmp = instance_.load(std::memory_order_consume); | |
18 | if (!tmp) { | |
19 | tmp = new T; | |
20 | instance_.store(tmp, std::memory_order_release); | |
21 | } | |
22 | } | |
23 | return *tmp; | |
24 | } | |
25 | private: | |
26 | static std::atomic<T *> instance_; | |
27 | static std::mutex instantiation_mutex; | |
28 | }; | |
29 | ||
30 | template<class T> | |
31 | std::atomic<T *> Singleton<T>::instance_(0); | |
32 | ||
33 | template<class T> | |
34 | std::mutex Singleton<T>::instantiation_mutex; | |
35 | ||
36 | #else | |
37 | ||
38 | #include "slmutex.h" | |
39 | ||
40 | template<class T> | |
41 | class Singleton { | |
42 | public: | |
43 | static T& instance() | |
44 | { | |
45 | T *tmp = _instance; | |
46 | if (!tmp) { | |
47 | Lockguard<MutexPosix> guard(&_instantiation_mutex); | |
48 | if (!tmp) { | |
49 | tmp = new T; | |
50 | _instance = tmp; | |
51 | } | |
52 | } | |
53 | return *tmp; | |
54 | } | |
55 | private: | |
56 | ||
57 | static T * _instance; | |
58 | ||
59 | static MutexPosix _instantiation_mutex; | |
60 | ||
61 | }; | |
62 | ||
63 | template<class T> | |
64 | T *Singleton<T>::_instance(0); | |
65 | ||
66 | template<class T> | |
67 | MutexPosix Singleton<T>::_instantiation_mutex; | |
68 | ||
69 | #endif | |
70 | ||
71 | #endif | |
72 | ||
73 |