]> git.uio.no Git - u/mrichter/AliRoot.git/blame - STARLIGHT/starlight/include/.svn/text-base/singleton.h.svn-base
STARLIGHT code and interface
[u/mrichter/AliRoot.git] / STARLIGHT / starlight / include / .svn / text-base / singleton.h.svn-base
CommitLineData
da32329d
AM
1#ifndef SINGLETON_H
2#define SINGLETON_H
3
4#ifdef CPP11
5#include <atomic>
6#include <mutex>
7
8
9template<class T>
10class Singleton {
11public:
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 }
25private:
26 static std::atomic<T *> instance_;
27 static std::mutex instantiation_mutex;
28};
29
30template<class T>
31std::atomic<T *> Singleton<T>::instance_(0);
32
33template<class T>
34std::mutex Singleton<T>::instantiation_mutex;
35
36#else
37
38#include "slmutex.h"
39
40template<class T>
41class Singleton {
42public:
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 }
55private:
56
57 static T * _instance;
58
59 static MutexPosix _instantiation_mutex;
60
61};
62
63template<class T>
64T *Singleton<T>::_instance(0);
65
66template<class T>
67MutexPosix Singleton<T>::_instantiation_mutex;
68
69#endif
70
71#endif
72
73