OLD | NEW |
---|---|
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. | 1 // Copyright (c) 2012 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 // The LazyInstance<Type, Traits> class manages a single instance of Type, | 5 // The LazyInstance<Type, Traits> class manages a single instance of Type, |
6 // which will be lazily created on the first time it's accessed. This class is | 6 // which will be lazily created on the first time it's accessed. This class is |
7 // useful for places you would normally use a function-level static, but you | 7 // useful for places you would normally use a function-level static, but you |
8 // need to have guaranteed thread-safety. The Type constructor will only ever | 8 // need to have guaranteed thread-safety. The Type constructor will only ever |
9 // be called once, even if two threads are racing to create the object. Get() | 9 // be called once, even if two threads are racing to create the object. Get() |
10 // and Pointer() will always return the same, completely initialized instance. | 10 // and Pointer() will always return the same, completely initialized instance. |
11 // When the instance is constructed it is registered with AtExitManager. The | 11 // When the instance is constructed it is registered with AtExitManager. The |
12 // destructor will be called on program exit. | 12 // destructor will be called on program exit. |
13 // | 13 // |
14 // LazyInstance is completely thread safe, assuming that you create it safely. | 14 // LazyInstance is completely thread safe, assuming that you create it safely. |
15 // The class was designed to be POD initialized, so it shouldn't require a | 15 // The class was designed to be POD initialized, so it shouldn't require a |
16 // static constructor. It really only makes sense to declare a LazyInstance as | 16 // static constructor. It really only makes sense to declare a LazyInstance as |
17 // a global variable using the LAZY_INSTANCE_INITIALIZER initializer. | 17 // a global variable using the LAZY_INSTANCE_INITIALIZER initializer. |
18 // | 18 // |
19 // LazyInstance is similar to Singleton, except it does not have the singleton | 19 // LazyInstance is similar to Singleton, except it does not have the singleton |
20 // property. You can have multiple LazyInstance's of the same type, and each | 20 // property. You can have multiple LazyInstance's of the same type, and each |
21 // will manage a unique instance. It also preallocates the space for Type, as | 21 // will manage a unique instance. It also preallocates the space for Type, as |
22 // to avoid allocating the Type instance on the heap. This may help with the | 22 // to avoid allocating the Type instance on the heap. This may help with the |
23 // performance of creating the instance, and reducing heap fragmentation. This | 23 // performance of creating the instance, and reducing heap fragmentation. This |
24 // requires that Type be a complete type so we can determine the size. | 24 // requires that Type be a complete type so we can determine the size. |
25 // | 25 // |
26 // Example usage: | 26 // Example usage: |
27 // static LazyInstance<MyClass> my_instance = LAZY_INSTANCE_INITIALIZER; | 27 // static LazyInstance<MyClass>::Leaky inst = LAZY_INSTANCE_INITIALIZER; |
28 // void SomeMethod() { | 28 // void SomeMethod() { |
29 // my_instance.Get().SomeMethod(); // MyClass::SomeMethod() | 29 // inst.Get().SomeMethod(); // MyClass::SomeMethod() |
30 // | 30 // |
31 // MyClass* ptr = my_instance.Pointer(); | 31 // MyClass* ptr = inst.Pointer(); |
32 // ptr->DoDoDo(); // MyClass::DoDoDo | 32 // ptr->DoDoDo(); // MyClass::DoDoDo |
33 // } | 33 // } |
34 | 34 |
35 #ifndef BASE_LAZY_INSTANCE_H_ | 35 #ifndef BASE_LAZY_INSTANCE_H_ |
36 #define BASE_LAZY_INSTANCE_H_ | 36 #define BASE_LAZY_INSTANCE_H_ |
37 | 37 |
38 #include <new> // For placement new. | 38 #include <new> // For placement new. |
39 | 39 |
40 #include "base/atomicops.h" | 40 #include "base/atomicops.h" |
41 #include "base/base_export.h" | 41 #include "base/base_export.h" |
42 #include "base/debug/leak_annotations.h" | 42 #include "base/debug/leak_annotations.h" |
43 #include "base/logging.h" | 43 #include "base/logging.h" |
44 #include "base/memory/aligned_memory.h" | 44 #include "base/memory/aligned_memory.h" |
45 #include "base/threading/thread_restrictions.h" | 45 #include "base/threading/thread_restrictions.h" |
46 | 46 |
47 // LazyInstance uses its own struct initializer-list style static | 47 // LazyInstance uses its own struct initializer-list style static |
48 // initialization, as base's LINKER_INITIALIZED requires a constructor and on | 48 // initialization, as base's LINKER_INITIALIZED requires a constructor and on |
49 // some compilers (notably gcc 4.4) this still ends up needing runtime | 49 // some compilers (notably gcc 4.4) this still ends up needing runtime |
50 // initialization. | 50 // initialization. |
51 #define LAZY_INSTANCE_INITIALIZER {0} | 51 #define LAZY_INSTANCE_INITIALIZER {0} |
52 | 52 |
53 namespace base { | 53 namespace base { |
54 | 54 |
55 template <typename Type> | 55 template <typename Type> |
56 struct DefaultLazyInstanceTraits { | 56 struct LazyInstanceTraitsBase { |
57 static const bool kRegisterOnExit = true; | |
58 #if DCHECK_IS_ON() | |
59 static const bool kAllowedToAccessOnNonjoinableThread = false; | |
60 #endif | |
61 | |
62 static Type* New(void* instance) { | 57 static Type* New(void* instance) { |
63 DCHECK_EQ(reinterpret_cast<uintptr_t>(instance) & (ALIGNOF(Type) - 1), 0u) | 58 DCHECK_EQ(reinterpret_cast<uintptr_t>(instance) & (ALIGNOF(Type) - 1), 0u); |
64 << ": Bad boy, the buffer passed to placement new is not aligned!\n" | |
65 "This may break some stuff like SSE-based optimizations assuming the " | |
66 "<Type> objects are word aligned."; | |
67 // Use placement new to initialize our instance in our preallocated space. | 59 // Use placement new to initialize our instance in our preallocated space. |
68 // The parenthesis is very important here to force POD type initialization. | 60 // The parenthesis is very important here to force POD type initialization. |
69 return new (instance) Type(); | 61 return new (instance) Type(); |
70 } | 62 } |
71 static void Delete(Type* instance) { | 63 |
64 static void CallDestructor(Type* instance) { | |
72 // Explicitly call the destructor. | 65 // Explicitly call the destructor. |
73 instance->~Type(); | 66 instance->~Type(); |
74 } | 67 } |
75 }; | 68 }; |
76 | 69 |
77 // We pull out some of the functionality into non-templated functions, so we | 70 // We pull out some of the functionality into non-templated functions, so we |
78 // can implement the more complicated pieces out of line in the .cc file. | 71 // can implement the more complicated pieces out of line in the .cc file. |
79 namespace internal { | 72 namespace internal { |
80 | 73 |
74 template <typename Type> | |
Nico
2017/03/07 21:43:02
add comment above this class that it generally sho
scottmg
2017/03/07 21:56:30
Done.
| |
75 struct DestructorAtExitLazyInstanceTraits { | |
76 static const bool kRegisterOnExit = true; | |
77 #if DCHECK_IS_ON() | |
78 static const bool kAllowedToAccessOnNonjoinableThread = false; | |
79 #endif | |
80 | |
81 static Type* New(void* instance) { | |
82 return LazyInstanceTraitsBase<Type>::New(instance); | |
83 } | |
84 | |
85 static void Delete(Type* instance) { | |
86 LazyInstanceTraitsBase<Type>::CallDestructor(instance); | |
87 } | |
88 }; | |
89 | |
81 // Use LazyInstance<T>::Leaky for a less-verbose call-site typedef; e.g.: | 90 // Use LazyInstance<T>::Leaky for a less-verbose call-site typedef; e.g.: |
82 // base::LazyInstance<T>::Leaky my_leaky_lazy_instance; | 91 // base::LazyInstance<T>::Leaky my_leaky_lazy_instance; |
83 // instead of: | 92 // instead of: |
84 // base::LazyInstance<T, base::internal::LeakyLazyInstanceTraits<T> > | 93 // base::LazyInstance<T, base::internal::LeakyLazyInstanceTraits<T> > |
85 // my_leaky_lazy_instance; | 94 // my_leaky_lazy_instance; |
86 // (especially when T is MyLongTypeNameImplClientHolderFactory). | 95 // (especially when T is MyLongTypeNameImplClientHolderFactory). |
87 // Only use this internal::-qualified verbose form to extend this traits class | 96 // Only use this internal::-qualified verbose form to extend this traits class |
88 // (depending on its implementation details). | 97 // (depending on its implementation details). |
89 template <typename Type> | 98 template <typename Type> |
90 struct LeakyLazyInstanceTraits { | 99 struct LeakyLazyInstanceTraits { |
91 static const bool kRegisterOnExit = false; | 100 static const bool kRegisterOnExit = false; |
92 #if DCHECK_IS_ON() | 101 #if DCHECK_IS_ON() |
93 static const bool kAllowedToAccessOnNonjoinableThread = true; | 102 static const bool kAllowedToAccessOnNonjoinableThread = true; |
94 #endif | 103 #endif |
95 | 104 |
96 static Type* New(void* instance) { | 105 static Type* New(void* instance) { |
97 ANNOTATE_SCOPED_MEMORY_LEAK; | 106 ANNOTATE_SCOPED_MEMORY_LEAK; |
98 return DefaultLazyInstanceTraits<Type>::New(instance); | 107 return LazyInstanceTraitsBase<Type>::New(instance); |
99 } | 108 } |
100 static void Delete(Type* instance) { | 109 static void Delete(Type* instance) { |
101 } | 110 } |
102 }; | 111 }; |
103 | 112 |
113 template <typename Type> | |
114 struct ErrorMustSelectLazyOrDestructorAtExitForLazyInstance {}; | |
115 | |
104 // Our AtomicWord doubles as a spinlock, where a value of | 116 // Our AtomicWord doubles as a spinlock, where a value of |
105 // kLazyInstanceStateCreating means the spinlock is being held for creation. | 117 // kLazyInstanceStateCreating means the spinlock is being held for creation. |
106 static const subtle::AtomicWord kLazyInstanceStateCreating = 1; | 118 static const subtle::AtomicWord kLazyInstanceStateCreating = 1; |
107 | 119 |
108 // Check if instance needs to be created. If so return true otherwise | 120 // Check if instance needs to be created. If so return true otherwise |
109 // if another thread has beat us, wait for instance to be created and | 121 // if another thread has beat us, wait for instance to be created and |
110 // return false. | 122 // return false. |
111 BASE_EXPORT bool NeedsLazyInstance(subtle::AtomicWord* state); | 123 BASE_EXPORT bool NeedsLazyInstance(subtle::AtomicWord* state); |
112 | 124 |
113 // After creating an instance, call this to register the dtor to be called | 125 // After creating an instance, call this to register the dtor to be called |
114 // at program exit and to update the atomic state to hold the |new_instance| | 126 // at program exit and to update the atomic state to hold the |new_instance| |
115 BASE_EXPORT void CompleteLazyInstance(subtle::AtomicWord* state, | 127 BASE_EXPORT void CompleteLazyInstance(subtle::AtomicWord* state, |
116 subtle::AtomicWord new_instance, | 128 subtle::AtomicWord new_instance, |
117 void* lazy_instance, | 129 void* lazy_instance, |
118 void (*dtor)(void*)); | 130 void (*dtor)(void*)); |
119 | 131 |
120 } // namespace internal | 132 } // namespace internal |
121 | 133 |
122 template <typename Type, typename Traits = DefaultLazyInstanceTraits<Type> > | 134 template < |
135 typename Type, | |
136 typename Traits = | |
137 internal::ErrorMustSelectLazyOrDestructorAtExitForLazyInstance<Type>> | |
Nico
2017/03/07 21:43:02
could this just not set a default for Traits?
scottmg
2017/03/07 21:56:30
That's what I tried at first, but then slightly od
| |
123 class LazyInstance { | 138 class LazyInstance { |
124 public: | 139 public: |
125 // Do not define a destructor, as doing so makes LazyInstance a | 140 // Do not define a destructor, as doing so makes LazyInstance a |
126 // non-POD-struct. We don't want that because then a static initializer will | 141 // non-POD-struct. We don't want that because then a static initializer will |
127 // be created to register the (empty) destructor with atexit() under MSVC, for | 142 // be created to register the (empty) destructor with atexit() under MSVC, for |
128 // example. We handle destruction of the contained Type class explicitly via | 143 // example. We handle destruction of the contained Type class explicitly via |
129 // the OnExit member function, where needed. | 144 // the OnExit member function, where needed. |
130 // ~LazyInstance() {} | 145 // ~LazyInstance() {} |
131 | 146 |
132 // Convenience typedef to avoid having to repeat Type for leaky lazy | 147 // Convenience typedef to avoid having to repeat Type for leaky lazy |
133 // instances. | 148 // instances. |
134 typedef LazyInstance<Type, internal::LeakyLazyInstanceTraits<Type> > Leaky; | 149 typedef LazyInstance<Type, internal::LeakyLazyInstanceTraits<Type>> Leaky; |
150 typedef LazyInstance<Type, internal::DestructorAtExitLazyInstanceTraits<Type>> | |
151 DestructorAtExit; | |
135 | 152 |
136 Type& Get() { | 153 Type& Get() { |
137 return *Pointer(); | 154 return *Pointer(); |
138 } | 155 } |
139 | 156 |
140 Type* Pointer() { | 157 Type* Pointer() { |
141 #if DCHECK_IS_ON() | 158 #if DCHECK_IS_ON() |
142 // Avoid making TLS lookup on release builds. | 159 // Avoid making TLS lookup on release builds. |
143 if (!Traits::kAllowedToAccessOnNonjoinableThread) | 160 if (!Traits::kAllowedToAccessOnNonjoinableThread) |
144 ThreadRestrictions::AssertSingletonAllowed(); | 161 ThreadRestrictions::AssertSingletonAllowed(); |
(...skipping 53 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... | |
198 LazyInstance<Type, Traits>* me = | 215 LazyInstance<Type, Traits>* me = |
199 reinterpret_cast<LazyInstance<Type, Traits>*>(lazy_instance); | 216 reinterpret_cast<LazyInstance<Type, Traits>*>(lazy_instance); |
200 Traits::Delete(me->instance()); | 217 Traits::Delete(me->instance()); |
201 subtle::NoBarrier_Store(&me->private_instance_, 0); | 218 subtle::NoBarrier_Store(&me->private_instance_, 0); |
202 } | 219 } |
203 }; | 220 }; |
204 | 221 |
205 } // namespace base | 222 } // namespace base |
206 | 223 |
207 #endif // BASE_LAZY_INSTANCE_H_ | 224 #endif // BASE_LAZY_INSTANCE_H_ |
OLD | NEW |