• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (c) 2009 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef BASE_SINGLETON_H_
6 #define BASE_SINGLETON_H_
7 
8 #include "base/at_exit.h"
9 #include "base/atomicops.h"
10 #include "base/dynamic_annotations.h"
11 #include "base/platform_thread.h"
12 
13 // Default traits for Singleton<Type>. Calls operator new and operator delete on
14 // the object. Registers automatic deletion at process exit.
15 // Overload if you need arguments or another memory allocation function.
16 template<typename Type>
17 struct DefaultSingletonTraits {
18   // Allocates the object.
NewDefaultSingletonTraits19   static Type* New() {
20     // The parenthesis is very important here; it forces POD type
21     // initialization.
22     return new Type();
23   }
24 
25   // Destroys the object.
DeleteDefaultSingletonTraits26   static void Delete(Type* x) {
27     delete x;
28   }
29 
30   // Set to true to automatically register deletion of the object on process
31   // exit. See below for the required call that makes this happen.
32   static const bool kRegisterAtExit = true;
33 };
34 
35 
36 // Alternate traits for use with the Singleton<Type>.  Identical to
37 // DefaultSingletonTraits except that the Singleton will not be cleaned up
38 // at exit.
39 template<typename Type>
40 struct LeakySingletonTraits : public DefaultSingletonTraits<Type> {
41   static const bool kRegisterAtExit = false;
42 };
43 
44 
45 // The Singleton<Type, Traits, DifferentiatingType> class manages a single
46 // instance of Type which will be created on first use and will be destroyed at
47 // normal process exit). The Trait::Delete function will not be called on
48 // abnormal process exit.
49 //
50 // DifferentiatingType is used as a key to differentiate two different
51 // singletons having the same memory allocation functions but serving a
52 // different purpose. This is mainly used for Locks serving different purposes.
53 //
54 // Example usages: (none are preferred, they all result in the same code)
55 //   1. FooClass* ptr = Singleton<FooClass>::get();
56 //      ptr->Bar();
57 //   2. Singleton<FooClass>()->Bar();
58 //   3. Singleton<FooClass>::get()->Bar();
59 //
60 // Singleton<> has no non-static members and doesn't need to actually be
61 // instantiated. It does no harm to instantiate it and use it as a class member
62 // or at global level since it is acting as a POD type.
63 //
64 // This class is itself thread-safe. The underlying Type must of course be
65 // thread-safe if you want to use it concurrently. Two parameters may be tuned
66 // depending on the user's requirements.
67 //
68 // Glossary:
69 //   RAE = kRegisterAtExit
70 //
71 // On every platform, if Traits::RAE is true, the singleton will be destroyed at
72 // process exit. More precisely it uses base::AtExitManager which requires an
73 // object of this type to be instantiated. AtExitManager mimics the semantics
74 // of atexit() such as LIFO order but under Windows is safer to call. For more
75 // information see at_exit.h.
76 //
77 // If Traits::RAE is false, the singleton will not be freed at process exit,
78 // thus the singleton will be leaked if it is ever accessed. Traits::RAE
79 // shouldn't be false unless absolutely necessary. Remember that the heap where
80 // the object is allocated may be destroyed by the CRT anyway.
81 //
82 // If you want to ensure that your class can only exist as a singleton, make
83 // its constructors private, and make DefaultSingletonTraits<> a friend:
84 //
85 //   #include "base/singleton.h"
86 //   class FooClass {
87 //    public:
88 //     void Bar() { ... }
89 //    private:
90 //     FooClass() { ... }
91 //     friend struct DefaultSingletonTraits<FooClass>;
92 //
93 //     DISALLOW_EVIL_CONSTRUCTORS(FooClass);
94 //   };
95 //
96 // Caveats:
97 // (a) Every call to get(), operator->() and operator*() incurs some overhead
98 //     (16ns on my P4/2.8GHz) to check whether the object has already been
99 //     initialized.  You may wish to cache the result of get(); it will not
100 //     change.
101 //
102 // (b) Your factory function must never throw an exception. This class is not
103 //     exception-safe.
104 //
105 template <typename Type,
106           typename Traits = DefaultSingletonTraits<Type>,
107           typename DifferentiatingType = Type>
108 class Singleton {
109  public:
110   // This class is safe to be constructed and copy-constructed since it has no
111   // member.
112 
113   // Return a pointer to the one true instance of the class.
get()114   static Type* get() {
115     // Our AtomicWord doubles as a spinlock, where a value of
116     // kBeingCreatedMarker means the spinlock is being held for creation.
117     static const base::subtle::AtomicWord kBeingCreatedMarker = 1;
118 
119     base::subtle::AtomicWord value = base::subtle::NoBarrier_Load(&instance_);
120     if (value != 0 && value != kBeingCreatedMarker) {
121       // See the corresponding HAPPENS_BEFORE below.
122       ANNOTATE_HAPPENS_AFTER(&instance_);
123       return reinterpret_cast<Type*>(value);
124     }
125 
126     // Object isn't created yet, maybe we will get to create it, let's try...
127     if (base::subtle::Acquire_CompareAndSwap(&instance_,
128                                              0,
129                                              kBeingCreatedMarker) == 0) {
130       // instance_ was NULL and is now kBeingCreatedMarker.  Only one thread
131       // will ever get here.  Threads might be spinning on us, and they will
132       // stop right after we do this store.
133       Type* newval = Traits::New();
134 
135       // This annotation helps race detectors recognize correct lock-less
136       // synchronization between different threads calling get().
137       // See the corresponding HAPPENS_AFTER below and above.
138       ANNOTATE_HAPPENS_BEFORE(&instance_);
139       base::subtle::Release_Store(
140           &instance_, reinterpret_cast<base::subtle::AtomicWord>(newval));
141 
142       if (Traits::kRegisterAtExit)
143         base::AtExitManager::RegisterCallback(OnExit, NULL);
144 
145       return newval;
146     }
147 
148     // We hit a race.  Another thread beat us and either:
149     // - Has the object in BeingCreated state
150     // - Already has the object created...
151     // We know value != NULL.  It could be kBeingCreatedMarker, or a valid ptr.
152     // Unless your constructor can be very time consuming, it is very unlikely
153     // to hit this race.  When it does, we just spin and yield the thread until
154     // the object has been created.
155     while (true) {
156       value = base::subtle::NoBarrier_Load(&instance_);
157       if (value != kBeingCreatedMarker)
158         break;
159       PlatformThread::YieldCurrentThread();
160     }
161 
162     // See the corresponding HAPPENS_BEFORE above.
163     ANNOTATE_HAPPENS_AFTER(&instance_);
164     return reinterpret_cast<Type*>(value);
165   }
166 
167   // Shortcuts.
168   Type& operator*() {
169     return *get();
170   }
171 
172   Type* operator->() {
173     return get();
174   }
175 
176  private:
177   // Adapter function for use with AtExit().  This should be called single
178   // threaded, but we might as well take the precautions anyway.
OnExit(void * unused)179   static void OnExit(void* unused) {
180     // AtExit should only ever be register after the singleton instance was
181     // created.  We should only ever get here with a valid instance_ pointer.
182     Traits::Delete(reinterpret_cast<Type*>(
183         base::subtle::NoBarrier_AtomicExchange(&instance_, 0)));
184   }
185   static base::subtle::AtomicWord instance_;
186 };
187 
188 template <typename Type, typename Traits, typename DifferentiatingType>
189 base::subtle::AtomicWord Singleton<Type, Traits, DifferentiatingType>::
190     instance_ = 0;
191 
192 #endif  // BASE_SINGLETON_H_
193