Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(636)

Side by Side Diff: base/memory/singleton.h

Issue 1308823002: Move Singleton and related structs to namespace base (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: ToT Created 5 years, 3 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « base/logging_win.cc ('k') | base/memory/singleton_unittest.cc » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 // Copyright (c) 2011 The Chromium Authors. All rights reserved. 1 // Copyright (c) 2011 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 // PLEASE READ: Do you really need a singleton? 5 // PLEASE READ: Do you really need a singleton?
6 // 6 //
7 // Singletons make it hard to determine the lifetime of an object, which can 7 // Singletons make it hard to determine the lifetime of an object, which can
8 // lead to buggy code and spurious crashes. 8 // lead to buggy code and spurious crashes.
9 // 9 //
10 // Instead of adding another singleton into the mix, try to identify either: 10 // Instead of adding another singleton into the mix, try to identify either:
(...skipping 18 matching lines...) Expand all
29 namespace internal { 29 namespace internal {
30 30
31 // Our AtomicWord doubles as a spinlock, where a value of 31 // Our AtomicWord doubles as a spinlock, where a value of
32 // kBeingCreatedMarker means the spinlock is being held for creation. 32 // kBeingCreatedMarker means the spinlock is being held for creation.
33 static const subtle::AtomicWord kBeingCreatedMarker = 1; 33 static const subtle::AtomicWord kBeingCreatedMarker = 1;
34 34
35 // We pull out some of the functionality into a non-templated function, so that 35 // We pull out some of the functionality into a non-templated function, so that
36 // we can implement the more complicated pieces out of line in the .cc file. 36 // we can implement the more complicated pieces out of line in the .cc file.
37 BASE_EXPORT subtle::AtomicWord WaitForInstance(subtle::AtomicWord* instance); 37 BASE_EXPORT subtle::AtomicWord WaitForInstance(subtle::AtomicWord* instance);
38 38
39 class DeleteTraceLogForTesting;
40
39 } // namespace internal 41 } // namespace internal
40 } // namespace base
41 42
42 // TODO(joth): Move more of this file into namespace base
43 43
44 // Default traits for Singleton<Type>. Calls operator new and operator delete on 44 // Default traits for Singleton<Type>. Calls operator new and operator delete on
45 // the object. Registers automatic deletion at process exit. 45 // the object. Registers automatic deletion at process exit.
46 // Overload if you need arguments or another memory allocation function. 46 // Overload if you need arguments or another memory allocation function.
47 template<typename Type> 47 template<typename Type>
48 struct DefaultSingletonTraits { 48 struct DefaultSingletonTraits {
49 // Allocates the object. 49 // Allocates the object.
50 static Type* New() { 50 static Type* New() {
51 // The parenthesis is very important here; it forces POD type 51 // The parenthesis is very important here; it forces POD type
52 // initialization. 52 // initialization.
(...skipping 50 matching lines...) Expand 10 before | Expand all | Expand 10 after
103 // this is also used in e.g. Chrome Frame, where you have to allow for the 103 // this is also used in e.g. Chrome Frame, where you have to allow for the
104 // possibility of loading briefly into someone else's process space, and 104 // possibility of loading briefly into someone else's process space, and
105 // so leaking is not an option, as that would sabotage the state of your host 105 // so leaking is not an option, as that would sabotage the state of your host
106 // process once you've unloaded. 106 // process once you've unloaded.
107 template <typename Type> 107 template <typename Type>
108 struct StaticMemorySingletonTraits { 108 struct StaticMemorySingletonTraits {
109 // WARNING: User has to deal with get() in the singleton class 109 // WARNING: User has to deal with get() in the singleton class
110 // this is traits for returning NULL. 110 // this is traits for returning NULL.
111 static Type* New() { 111 static Type* New() {
112 // Only constructs once and returns pointer; otherwise returns NULL. 112 // Only constructs once and returns pointer; otherwise returns NULL.
113 if (base::subtle::NoBarrier_AtomicExchange(&dead_, 1)) 113 if (subtle::NoBarrier_AtomicExchange(&dead_, 1))
114 return NULL; 114 return NULL;
115 115
116 return new(buffer_.void_data()) Type(); 116 return new(buffer_.void_data()) Type();
117 } 117 }
118 118
119 static void Delete(Type* p) { 119 static void Delete(Type* p) {
120 if (p != NULL) 120 if (p != NULL)
121 p->Type::~Type(); 121 p->Type::~Type();
122 } 122 }
123 123
124 static const bool kRegisterAtExit = true; 124 static const bool kRegisterAtExit = true;
125 static const bool kAllowedToAccessOnNonjoinableThread = true; 125 static const bool kAllowedToAccessOnNonjoinableThread = true;
126 126
127 // Exposed for unittesting. 127 // Exposed for unittesting.
128 static void Resurrect() { 128 static void Resurrect() { subtle::NoBarrier_Store(&dead_, 0); }
129 base::subtle::NoBarrier_Store(&dead_, 0);
130 }
131 129
132 private: 130 private:
133 static base::AlignedMemory<sizeof(Type), ALIGNOF(Type)> buffer_; 131 static AlignedMemory<sizeof(Type), ALIGNOF(Type)> buffer_;
134 // Signal the object was already deleted, so it is not revived. 132 // Signal the object was already deleted, so it is not revived.
135 static base::subtle::Atomic32 dead_; 133 static subtle::Atomic32 dead_;
136 }; 134 };
137 135
138 template <typename Type> base::AlignedMemory<sizeof(Type), ALIGNOF(Type)> 136 template <typename Type>
137 AlignedMemory<sizeof(Type), ALIGNOF(Type)>
139 StaticMemorySingletonTraits<Type>::buffer_; 138 StaticMemorySingletonTraits<Type>::buffer_;
140 template <typename Type> base::subtle::Atomic32 139 template <typename Type>
141 StaticMemorySingletonTraits<Type>::dead_ = 0; 140 subtle::Atomic32 StaticMemorySingletonTraits<Type>::dead_ = 0;
142 141
143 // The Singleton<Type, Traits, DifferentiatingType> class manages a single 142 // The Singleton<Type, Traits, DifferentiatingType> class manages a single
144 // instance of Type which will be created on first use and will be destroyed at 143 // instance of Type which will be created on first use and will be destroyed at
145 // normal process exit). The Trait::Delete function will not be called on 144 // normal process exit). The Trait::Delete function will not be called on
146 // abnormal process exit. 145 // abnormal process exit.
147 // 146 //
148 // DifferentiatingType is used as a key to differentiate two different 147 // DifferentiatingType is used as a key to differentiate two different
149 // singletons having the same memory allocation functions but serving a 148 // singletons having the same memory allocation functions but serving a
150 // different purpose. This is mainly used for Locks serving different purposes. 149 // different purpose. This is mainly used for Locks serving different purposes.
151 // 150 //
(...skipping 31 matching lines...) Expand 10 before | Expand all | Expand 10 after
183 // instantiated. 182 // instantiated.
184 // 183 //
185 // This class is itself thread-safe. The underlying Type must of course be 184 // This class is itself thread-safe. The underlying Type must of course be
186 // thread-safe if you want to use it concurrently. Two parameters may be tuned 185 // thread-safe if you want to use it concurrently. Two parameters may be tuned
187 // depending on the user's requirements. 186 // depending on the user's requirements.
188 // 187 //
189 // Glossary: 188 // Glossary:
190 // RAE = kRegisterAtExit 189 // RAE = kRegisterAtExit
191 // 190 //
192 // On every platform, if Traits::RAE is true, the singleton will be destroyed at 191 // On every platform, if Traits::RAE is true, the singleton will be destroyed at
193 // process exit. More precisely it uses base::AtExitManager which requires an 192 // process exit. More precisely it uses AtExitManager which requires an
194 // object of this type to be instantiated. AtExitManager mimics the semantics 193 // object of this type to be instantiated. AtExitManager mimics the semantics
195 // of atexit() such as LIFO order but under Windows is safer to call. For more 194 // of atexit() such as LIFO order but under Windows is safer to call. For more
196 // information see at_exit.h. 195 // information see at_exit.h.
197 // 196 //
198 // If Traits::RAE is false, the singleton will not be freed at process exit, 197 // If Traits::RAE is false, the singleton will not be freed at process exit,
199 // thus the singleton will be leaked if it is ever accessed. Traits::RAE 198 // thus the singleton will be leaked if it is ever accessed. Traits::RAE
200 // shouldn't be false unless absolutely necessary. Remember that the heap where 199 // shouldn't be false unless absolutely necessary. Remember that the heap where
201 // the object is allocated may be destroyed by the CRT anyway. 200 // the object is allocated may be destroyed by the CRT anyway.
202 // 201 //
203 // Caveats: 202 // Caveats:
204 // (a) Every call to get(), operator->() and operator*() incurs some overhead 203 // (a) Every call to get(), operator->() and operator*() incurs some overhead
205 // (16ns on my P4/2.8GHz) to check whether the object has already been 204 // (16ns on my P4/2.8GHz) to check whether the object has already been
206 // initialized. You may wish to cache the result of get(); it will not 205 // initialized. You may wish to cache the result of get(); it will not
207 // change. 206 // change.
208 // 207 //
209 // (b) Your factory function must never throw an exception. This class is not 208 // (b) Your factory function must never throw an exception. This class is not
210 // exception-safe. 209 // exception-safe.
211 // 210 //
211
212 template <typename Type, 212 template <typename Type,
213 typename Traits = DefaultSingletonTraits<Type>, 213 typename Traits = DefaultSingletonTraits<Type>,
214 typename DifferentiatingType = Type> 214 typename DifferentiatingType = Type>
215 class Singleton { 215 class Singleton {
216 private: 216 private:
217 // Classes using the Singleton<T> pattern should declare a GetInstance() 217 // Classes using the Singleton<T> pattern should declare a GetInstance()
218 // method and call Singleton::get() from within that. 218 // method and call Singleton::get() from within that.
219 friend Type* Type::GetInstance(); 219 friend Type* Type::GetInstance();
220 220
221 // Allow TraceLog tests to test tracing after OnExit. 221 // Allow TraceLog tests to test tracing after OnExit.
222 friend class DeleteTraceLogForTesting; 222 friend class internal::DeleteTraceLogForTesting;
223 223
224 // This class is safe to be constructed and copy-constructed since it has no 224 // This class is safe to be constructed and copy-constructed since it has no
225 // member. 225 // member.
226 226
227 // Return a pointer to the one true instance of the class. 227 // Return a pointer to the one true instance of the class.
228 static Type* get() { 228 static Type* get() {
229 #ifndef NDEBUG 229 #ifndef NDEBUG
230 // Avoid making TLS lookup on release builds. 230 // Avoid making TLS lookup on release builds.
231 if (!Traits::kAllowedToAccessOnNonjoinableThread) 231 if (!Traits::kAllowedToAccessOnNonjoinableThread)
232 base::ThreadRestrictions::AssertSingletonAllowed(); 232 ThreadRestrictions::AssertSingletonAllowed();
233 #endif 233 #endif
234 234
235 // The load has acquire memory ordering as the thread which reads the 235 // The load has acquire memory ordering as the thread which reads the
236 // instance_ pointer must acquire visibility over the singleton data. 236 // instance_ pointer must acquire visibility over the singleton data.
237 base::subtle::AtomicWord value = base::subtle::Acquire_Load(&instance_); 237 subtle::AtomicWord value = subtle::Acquire_Load(&instance_);
238 if (value != 0 && value != base::internal::kBeingCreatedMarker) { 238 if (value != 0 && value != internal::kBeingCreatedMarker) {
239 return reinterpret_cast<Type*>(value); 239 return reinterpret_cast<Type*>(value);
240 } 240 }
241 241
242 // Object isn't created yet, maybe we will get to create it, let's try... 242 // Object isn't created yet, maybe we will get to create it, let's try...
243 if (base::subtle::Acquire_CompareAndSwap( 243 if (subtle::Acquire_CompareAndSwap(&instance_, 0,
244 &instance_, 0, base::internal::kBeingCreatedMarker) == 0) { 244 internal::kBeingCreatedMarker) == 0) {
245 // instance_ was NULL and is now kBeingCreatedMarker. Only one thread 245 // instance_ was NULL and is now kBeingCreatedMarker. Only one thread
246 // will ever get here. Threads might be spinning on us, and they will 246 // will ever get here. Threads might be spinning on us, and they will
247 // stop right after we do this store. 247 // stop right after we do this store.
248 Type* newval = Traits::New(); 248 Type* newval = Traits::New();
249 249
250 // Releases the visibility over instance_ to the readers. 250 // Releases the visibility over instance_ to the readers.
251 base::subtle::Release_Store( 251 subtle::Release_Store(&instance_,
252 &instance_, reinterpret_cast<base::subtle::AtomicWord>(newval)); 252 reinterpret_cast<subtle::AtomicWord>(newval));
253 253
254 if (newval != NULL && Traits::kRegisterAtExit) 254 if (newval != NULL && Traits::kRegisterAtExit)
255 base::AtExitManager::RegisterCallback(OnExit, NULL); 255 AtExitManager::RegisterCallback(OnExit, NULL);
256 256
257 return newval; 257 return newval;
258 } 258 }
259 259
260 // We hit a race. Wait for the other thread to complete it. 260 // We hit a race. Wait for the other thread to complete it.
261 value = base::internal::WaitForInstance(&instance_); 261 value = internal::WaitForInstance(&instance_);
262 262
263 return reinterpret_cast<Type*>(value); 263 return reinterpret_cast<Type*>(value);
264 } 264 }
265 265
266 // Adapter function for use with AtExit(). This should be called single 266 // Adapter function for use with AtExit(). This should be called single
267 // threaded, so don't use atomic operations. 267 // threaded, so don't use atomic operations.
268 // Calling OnExit while singleton is in use by other threads is a mistake. 268 // Calling OnExit while singleton is in use by other threads is a mistake.
269 static void OnExit(void* /*unused*/) { 269 static void OnExit(void* /*unused*/) {
270 // AtExit should only ever be register after the singleton instance was 270 // AtExit should only ever be register after the singleton instance was
271 // created. We should only ever get here with a valid instance_ pointer. 271 // created. We should only ever get here with a valid instance_ pointer.
272 Traits::Delete( 272 Traits::Delete(reinterpret_cast<Type*>(subtle::NoBarrier_Load(&instance_)));
273 reinterpret_cast<Type*>(base::subtle::NoBarrier_Load(&instance_)));
274 instance_ = 0; 273 instance_ = 0;
275 } 274 }
276 static base::subtle::AtomicWord instance_; 275 static subtle::AtomicWord instance_;
277 }; 276 };
278 277
279 template <typename Type, typename Traits, typename DifferentiatingType> 278 template <typename Type, typename Traits, typename DifferentiatingType>
280 base::subtle::AtomicWord Singleton<Type, Traits, DifferentiatingType>:: 279 subtle::AtomicWord Singleton<Type, Traits, DifferentiatingType>::instance_ = 0;
281 instance_ = 0; 280
281 } // namespace base
282 282
283 #endif // BASE_MEMORY_SINGLETON_H_ 283 #endif // BASE_MEMORY_SINGLETON_H_
OLDNEW
« no previous file with comments | « base/logging_win.cc ('k') | base/memory/singleton_unittest.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698