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 // This traits class causes destruction the contained Type at process exit via |
| 75 // AtExitManager. This is probably generally not what you want. Instead, prefer |
| 76 // Leaky below. |
| 77 template <typename Type> |
| 78 struct DestructorAtExitLazyInstanceTraits { |
| 79 static const bool kRegisterOnExit = true; |
| 80 #if DCHECK_IS_ON() |
| 81 static const bool kAllowedToAccessOnNonjoinableThread = false; |
| 82 #endif |
| 83 |
| 84 static Type* New(void* instance) { |
| 85 return LazyInstanceTraitsBase<Type>::New(instance); |
| 86 } |
| 87 |
| 88 static void Delete(Type* instance) { |
| 89 LazyInstanceTraitsBase<Type>::CallDestructor(instance); |
| 90 } |
| 91 }; |
| 92 |
81 // Use LazyInstance<T>::Leaky for a less-verbose call-site typedef; e.g.: | 93 // Use LazyInstance<T>::Leaky for a less-verbose call-site typedef; e.g.: |
82 // base::LazyInstance<T>::Leaky my_leaky_lazy_instance; | 94 // base::LazyInstance<T>::Leaky my_leaky_lazy_instance; |
83 // instead of: | 95 // instead of: |
84 // base::LazyInstance<T, base::internal::LeakyLazyInstanceTraits<T> > | 96 // base::LazyInstance<T, base::internal::LeakyLazyInstanceTraits<T> > |
85 // my_leaky_lazy_instance; | 97 // my_leaky_lazy_instance; |
86 // (especially when T is MyLongTypeNameImplClientHolderFactory). | 98 // (especially when T is MyLongTypeNameImplClientHolderFactory). |
87 // Only use this internal::-qualified verbose form to extend this traits class | 99 // Only use this internal::-qualified verbose form to extend this traits class |
88 // (depending on its implementation details). | 100 // (depending on its implementation details). |
89 template <typename Type> | 101 template <typename Type> |
90 struct LeakyLazyInstanceTraits { | 102 struct LeakyLazyInstanceTraits { |
91 static const bool kRegisterOnExit = false; | 103 static const bool kRegisterOnExit = false; |
92 #if DCHECK_IS_ON() | 104 #if DCHECK_IS_ON() |
93 static const bool kAllowedToAccessOnNonjoinableThread = true; | 105 static const bool kAllowedToAccessOnNonjoinableThread = true; |
94 #endif | 106 #endif |
95 | 107 |
96 static Type* New(void* instance) { | 108 static Type* New(void* instance) { |
97 ANNOTATE_SCOPED_MEMORY_LEAK; | 109 ANNOTATE_SCOPED_MEMORY_LEAK; |
98 return DefaultLazyInstanceTraits<Type>::New(instance); | 110 return LazyInstanceTraitsBase<Type>::New(instance); |
99 } | 111 } |
100 static void Delete(Type* instance) { | 112 static void Delete(Type* instance) { |
101 } | 113 } |
102 }; | 114 }; |
103 | 115 |
| 116 template <typename Type> |
| 117 struct ErrorMustSelectLazyOrDestructorAtExitForLazyInstance {}; |
| 118 |
104 // Our AtomicWord doubles as a spinlock, where a value of | 119 // Our AtomicWord doubles as a spinlock, where a value of |
105 // kLazyInstanceStateCreating means the spinlock is being held for creation. | 120 // kLazyInstanceStateCreating means the spinlock is being held for creation. |
106 static const subtle::AtomicWord kLazyInstanceStateCreating = 1; | 121 static const subtle::AtomicWord kLazyInstanceStateCreating = 1; |
107 | 122 |
108 // Check if instance needs to be created. If so return true otherwise | 123 // 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 | 124 // if another thread has beat us, wait for instance to be created and |
110 // return false. | 125 // return false. |
111 BASE_EXPORT bool NeedsLazyInstance(subtle::AtomicWord* state); | 126 BASE_EXPORT bool NeedsLazyInstance(subtle::AtomicWord* state); |
112 | 127 |
113 // After creating an instance, call this to register the dtor to be called | 128 // 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| | 129 // at program exit and to update the atomic state to hold the |new_instance| |
115 BASE_EXPORT void CompleteLazyInstance(subtle::AtomicWord* state, | 130 BASE_EXPORT void CompleteLazyInstance(subtle::AtomicWord* state, |
116 subtle::AtomicWord new_instance, | 131 subtle::AtomicWord new_instance, |
117 void* lazy_instance, | 132 void* lazy_instance, |
118 void (*dtor)(void*)); | 133 void (*dtor)(void*)); |
119 | 134 |
120 } // namespace internal | 135 } // namespace internal |
121 | 136 |
122 template <typename Type, typename Traits = DefaultLazyInstanceTraits<Type> > | 137 template < |
| 138 typename Type, |
| 139 typename Traits = |
| 140 internal::ErrorMustSelectLazyOrDestructorAtExitForLazyInstance<Type>> |
123 class LazyInstance { | 141 class LazyInstance { |
124 public: | 142 public: |
125 // Do not define a destructor, as doing so makes LazyInstance a | 143 // 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 | 144 // 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 | 145 // be created to register the (empty) destructor with atexit() under MSVC, for |
128 // example. We handle destruction of the contained Type class explicitly via | 146 // example. We handle destruction of the contained Type class explicitly via |
129 // the OnExit member function, where needed. | 147 // the OnExit member function, where needed. |
130 // ~LazyInstance() {} | 148 // ~LazyInstance() {} |
131 | 149 |
132 // Convenience typedef to avoid having to repeat Type for leaky lazy | 150 // Convenience typedef to avoid having to repeat Type for leaky lazy |
133 // instances. | 151 // instances. |
134 typedef LazyInstance<Type, internal::LeakyLazyInstanceTraits<Type> > Leaky; | 152 typedef LazyInstance<Type, internal::LeakyLazyInstanceTraits<Type>> Leaky; |
| 153 typedef LazyInstance<Type, internal::DestructorAtExitLazyInstanceTraits<Type>> |
| 154 DestructorAtExit; |
135 | 155 |
136 Type& Get() { | 156 Type& Get() { |
137 return *Pointer(); | 157 return *Pointer(); |
138 } | 158 } |
139 | 159 |
140 Type* Pointer() { | 160 Type* Pointer() { |
141 #if DCHECK_IS_ON() | 161 #if DCHECK_IS_ON() |
142 // Avoid making TLS lookup on release builds. | 162 // Avoid making TLS lookup on release builds. |
143 if (!Traits::kAllowedToAccessOnNonjoinableThread) | 163 if (!Traits::kAllowedToAccessOnNonjoinableThread) |
144 ThreadRestrictions::AssertSingletonAllowed(); | 164 ThreadRestrictions::AssertSingletonAllowed(); |
(...skipping 53 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
198 LazyInstance<Type, Traits>* me = | 218 LazyInstance<Type, Traits>* me = |
199 reinterpret_cast<LazyInstance<Type, Traits>*>(lazy_instance); | 219 reinterpret_cast<LazyInstance<Type, Traits>*>(lazy_instance); |
200 Traits::Delete(me->instance()); | 220 Traits::Delete(me->instance()); |
201 subtle::NoBarrier_Store(&me->private_instance_, 0); | 221 subtle::NoBarrier_Store(&me->private_instance_, 0); |
202 } | 222 } |
203 }; | 223 }; |
204 | 224 |
205 } // namespace base | 225 } // namespace base |
206 | 226 |
207 #endif // BASE_LAZY_INSTANCE_H_ | 227 #endif // BASE_LAZY_INSTANCE_H_ |
OLD | NEW |