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

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: Remove todo 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
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 19 matching lines...) Expand all
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 } // namespace internal 39 } // namespace internal
40 } // namespace base
41 40
42 // TODO(joth): Move more of this file into namespace base
43 41
44 // Default traits for Singleton<Type>. Calls operator new and operator delete on 42 // Default traits for Singleton<Type>. Calls operator new and operator delete on
45 // the object. Registers automatic deletion at process exit. 43 // the object. Registers automatic deletion at process exit.
46 // Overload if you need arguments or another memory allocation function. 44 // Overload if you need arguments or another memory allocation function.
47 template<typename Type> 45 template<typename Type>
48 struct DefaultSingletonTraits { 46 struct DefaultSingletonTraits {
49 // Allocates the object. 47 // Allocates the object.
50 static Type* New() { 48 static Type* New() {
51 // The parenthesis is very important here; it forces POD type 49 // The parenthesis is very important here; it forces POD type
52 // initialization. 50 // 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 101 // 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 102 // 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 103 // so leaking is not an option, as that would sabotage the state of your host
106 // process once you've unloaded. 104 // process once you've unloaded.
107 template <typename Type> 105 template <typename Type>
108 struct StaticMemorySingletonTraits { 106 struct StaticMemorySingletonTraits {
109 // WARNING: User has to deal with get() in the singleton class 107 // WARNING: User has to deal with get() in the singleton class
110 // this is traits for returning NULL. 108 // this is traits for returning NULL.
111 static Type* New() { 109 static Type* New() {
112 // Only constructs once and returns pointer; otherwise returns NULL. 110 // Only constructs once and returns pointer; otherwise returns NULL.
113 if (base::subtle::NoBarrier_AtomicExchange(&dead_, 1)) 111 if (subtle::NoBarrier_AtomicExchange(&dead_, 1))
114 return NULL; 112 return NULL;
115 113
116 return new(buffer_.void_data()) Type(); 114 return new(buffer_.void_data()) Type();
117 } 115 }
118 116
119 static void Delete(Type* p) { 117 static void Delete(Type* p) {
120 if (p != NULL) 118 if (p != NULL)
121 p->Type::~Type(); 119 p->Type::~Type();
122 } 120 }
123 121
124 static const bool kRegisterAtExit = true; 122 static const bool kRegisterAtExit = true;
125 static const bool kAllowedToAccessOnNonjoinableThread = true; 123 static const bool kAllowedToAccessOnNonjoinableThread = true;
126 124
127 // Exposed for unittesting. 125 // Exposed for unittesting.
128 static void Resurrect() { 126 static void Resurrect() { subtle::NoBarrier_Store(&dead_, 0); }
129 base::subtle::NoBarrier_Store(&dead_, 0);
130 }
131 127
132 private: 128 private:
133 static base::AlignedMemory<sizeof(Type), ALIGNOF(Type)> buffer_; 129 static AlignedMemory<sizeof(Type), ALIGNOF(Type)> buffer_;
134 // Signal the object was already deleted, so it is not revived. 130 // Signal the object was already deleted, so it is not revived.
135 static base::subtle::Atomic32 dead_; 131 static subtle::Atomic32 dead_;
136 }; 132 };
137 133
138 template <typename Type> base::AlignedMemory<sizeof(Type), ALIGNOF(Type)> 134 template <typename Type>
135 AlignedMemory<sizeof(Type), ALIGNOF(Type)>
139 StaticMemorySingletonTraits<Type>::buffer_; 136 StaticMemorySingletonTraits<Type>::buffer_;
140 template <typename Type> base::subtle::Atomic32 137 template <typename Type>
141 StaticMemorySingletonTraits<Type>::dead_ = 0; 138 subtle::Atomic32 StaticMemorySingletonTraits<Type>::dead_ = 0;
142 139
143 // The Singleton<Type, Traits, DifferentiatingType> class manages a single 140 // 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 141 // 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 142 // normal process exit). The Trait::Delete function will not be called on
146 // abnormal process exit. 143 // abnormal process exit.
147 // 144 //
148 // DifferentiatingType is used as a key to differentiate two different 145 // DifferentiatingType is used as a key to differentiate two different
149 // singletons having the same memory allocation functions but serving a 146 // singletons having the same memory allocation functions but serving a
150 // different purpose. This is mainly used for Locks serving different purposes. 147 // different purpose. This is mainly used for Locks serving different purposes.
151 // 148 //
(...skipping 31 matching lines...) Expand 10 before | Expand all | Expand 10 after
183 // instantiated. 180 // instantiated.
184 // 181 //
185 // This class is itself thread-safe. The underlying Type must of course be 182 // 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 183 // thread-safe if you want to use it concurrently. Two parameters may be tuned
187 // depending on the user's requirements. 184 // depending on the user's requirements.
188 // 185 //
189 // Glossary: 186 // Glossary:
190 // RAE = kRegisterAtExit 187 // RAE = kRegisterAtExit
191 // 188 //
192 // On every platform, if Traits::RAE is true, the singleton will be destroyed at 189 // 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 190 // process exit. More precisely it uses AtExitManager which requires an
194 // object of this type to be instantiated. AtExitManager mimics the semantics 191 // 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 192 // of atexit() such as LIFO order but under Windows is safer to call. For more
196 // information see at_exit.h. 193 // information see at_exit.h.
197 // 194 //
198 // If Traits::RAE is false, the singleton will not be freed at process exit, 195 // 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 196 // 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 197 // shouldn't be false unless absolutely necessary. Remember that the heap where
201 // the object is allocated may be destroyed by the CRT anyway. 198 // the object is allocated may be destroyed by the CRT anyway.
202 // 199 //
203 // Caveats: 200 // Caveats:
(...skipping 18 matching lines...) Expand all
222 friend class DeleteTraceLogForTesting; 219 friend class DeleteTraceLogForTesting;
223 220
224 // This class is safe to be constructed and copy-constructed since it has no 221 // This class is safe to be constructed and copy-constructed since it has no
225 // member. 222 // member.
226 223
227 // Return a pointer to the one true instance of the class. 224 // Return a pointer to the one true instance of the class.
228 static Type* get() { 225 static Type* get() {
229 #ifndef NDEBUG 226 #ifndef NDEBUG
230 // Avoid making TLS lookup on release builds. 227 // Avoid making TLS lookup on release builds.
231 if (!Traits::kAllowedToAccessOnNonjoinableThread) 228 if (!Traits::kAllowedToAccessOnNonjoinableThread)
232 base::ThreadRestrictions::AssertSingletonAllowed(); 229 ThreadRestrictions::AssertSingletonAllowed();
233 #endif 230 #endif
234 231
235 // The load has acquire memory ordering as the thread which reads the 232 // The load has acquire memory ordering as the thread which reads the
236 // instance_ pointer must acquire visibility over the singleton data. 233 // instance_ pointer must acquire visibility over the singleton data.
237 base::subtle::AtomicWord value = base::subtle::Acquire_Load(&instance_); 234 subtle::AtomicWord value = subtle::Acquire_Load(&instance_);
238 if (value != 0 && value != base::internal::kBeingCreatedMarker) { 235 if (value != 0 && value != internal::kBeingCreatedMarker) {
239 return reinterpret_cast<Type*>(value); 236 return reinterpret_cast<Type*>(value);
240 } 237 }
241 238
242 // Object isn't created yet, maybe we will get to create it, let's try... 239 // Object isn't created yet, maybe we will get to create it, let's try...
243 if (base::subtle::Acquire_CompareAndSwap( 240 if (subtle::Acquire_CompareAndSwap(&instance_, 0,
244 &instance_, 0, base::internal::kBeingCreatedMarker) == 0) { 241 internal::kBeingCreatedMarker) == 0) {
245 // instance_ was NULL and is now kBeingCreatedMarker. Only one thread 242 // instance_ was NULL and is now kBeingCreatedMarker. Only one thread
246 // will ever get here. Threads might be spinning on us, and they will 243 // will ever get here. Threads might be spinning on us, and they will
247 // stop right after we do this store. 244 // stop right after we do this store.
248 Type* newval = Traits::New(); 245 Type* newval = Traits::New();
249 246
250 // Releases the visibility over instance_ to the readers. 247 // Releases the visibility over instance_ to the readers.
251 base::subtle::Release_Store( 248 subtle::Release_Store(&instance_,
252 &instance_, reinterpret_cast<base::subtle::AtomicWord>(newval)); 249 reinterpret_cast<subtle::AtomicWord>(newval));
253 250
254 if (newval != NULL && Traits::kRegisterAtExit) 251 if (newval != NULL && Traits::kRegisterAtExit)
255 base::AtExitManager::RegisterCallback(OnExit, NULL); 252 AtExitManager::RegisterCallback(OnExit, NULL);
256 253
257 return newval; 254 return newval;
258 } 255 }
259 256
260 // We hit a race. Wait for the other thread to complete it. 257 // We hit a race. Wait for the other thread to complete it.
261 value = base::internal::WaitForInstance(&instance_); 258 value = internal::WaitForInstance(&instance_);
262 259
263 return reinterpret_cast<Type*>(value); 260 return reinterpret_cast<Type*>(value);
264 } 261 }
265 262
266 // Adapter function for use with AtExit(). This should be called single 263 // Adapter function for use with AtExit(). This should be called single
267 // threaded, so don't use atomic operations. 264 // threaded, so don't use atomic operations.
268 // Calling OnExit while singleton is in use by other threads is a mistake. 265 // Calling OnExit while singleton is in use by other threads is a mistake.
269 static void OnExit(void* /*unused*/) { 266 static void OnExit(void* /*unused*/) {
270 // AtExit should only ever be register after the singleton instance was 267 // AtExit should only ever be register after the singleton instance was
271 // created. We should only ever get here with a valid instance_ pointer. 268 // created. We should only ever get here with a valid instance_ pointer.
272 Traits::Delete( 269 Traits::Delete(reinterpret_cast<Type*>(subtle::NoBarrier_Load(&instance_)));
273 reinterpret_cast<Type*>(base::subtle::NoBarrier_Load(&instance_)));
274 instance_ = 0; 270 instance_ = 0;
275 } 271 }
276 static base::subtle::AtomicWord instance_; 272 static subtle::AtomicWord instance_;
277 }; 273 };
278 274
279 template <typename Type, typename Traits, typename DifferentiatingType> 275 template <typename Type, typename Traits, typename DifferentiatingType>
280 base::subtle::AtomicWord Singleton<Type, Traits, DifferentiatingType>:: 276 subtle::AtomicWord Singleton<Type, Traits, DifferentiatingType>::instance_ = 0;
281 instance_ = 0;
282 277
278 } // namespace base
Mark Mentovai 2015/08/31 14:00:51 Blank line after this.
283 #endif // BASE_MEMORY_SINGLETON_H_ 279 #endif // BASE_MEMORY_SINGLETON_H_
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698