[email protected] | 9fc4416 | 2012-01-23 22:56:41 | [diff] [blame] | 1 | // Copyright (c) 2012 The Chromium Authors. All rights reserved. |
[email protected] | 30039e6 | 2008-09-08 14:11:13 | [diff] [blame] | 2 | // Use of this source code is governed by a BSD-style license that can be |
| 3 | // found in the LICENSE file. |
| 4 | |
| 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 |
| 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 |
| 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. |
| 11 | // When the instance is constructed it is registered with AtExitManager. The |
| 12 | // destructor will be called on program exit. |
| 13 | // |
| 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 |
| 16 | // static constructor. It really only makes sense to declare a LazyInstance as |
[email protected] | 6de0fd1d | 2011-11-15 13:31:49 | [diff] [blame] | 17 | // a global variable using the LAZY_INSTANCE_INITIALIZER initializer. |
[email protected] | 30039e6 | 2008-09-08 14:11:13 | [diff] [blame] | 18 | // |
| 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 |
| 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 |
| 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. |
| 25 | // |
| 26 | // Example usage: |
scottmg | 5e65e3a | 2017-03-08 08:48:46 | [diff] [blame] | 27 | // static LazyInstance<MyClass>::Leaky inst = LAZY_INSTANCE_INITIALIZER; |
[email protected] | 30039e6 | 2008-09-08 14:11:13 | [diff] [blame] | 28 | // void SomeMethod() { |
scottmg | 5e65e3a | 2017-03-08 08:48:46 | [diff] [blame] | 29 | // inst.Get().SomeMethod(); // MyClass::SomeMethod() |
[email protected] | 52a261f | 2009-03-03 15:01:12 | [diff] [blame] | 30 | // |
scottmg | 5e65e3a | 2017-03-08 08:48:46 | [diff] [blame] | 31 | // MyClass* ptr = inst.Pointer(); |
[email protected] | 30039e6 | 2008-09-08 14:11:13 | [diff] [blame] | 32 | // ptr->DoDoDo(); // MyClass::DoDoDo |
| 33 | // } |
| 34 | |
| 35 | #ifndef BASE_LAZY_INSTANCE_H_ |
| 36 | #define BASE_LAZY_INSTANCE_H_ |
| 37 | |
[email protected] | 359d2bf | 2010-11-19 20:34:18 | [diff] [blame] | 38 | #include <new> // For placement new. |
| 39 | |
[email protected] | 30039e6 | 2008-09-08 14:11:13 | [diff] [blame] | 40 | #include "base/atomicops.h" |
[email protected] | 0bea725 | 2011-08-05 15:34:00 | [diff] [blame] | 41 | #include "base/base_export.h" |
[email protected] | b2206da5 | 2013-06-07 22:09:32 | [diff] [blame] | 42 | #include "base/debug/leak_annotations.h" |
[email protected] | e4a638f76 | 2011-10-21 19:46:00 | [diff] [blame] | 43 | #include "base/logging.h" |
[email protected] | 34b9963 | 2011-01-01 01:01:06 | [diff] [blame] | 44 | #include "base/threading/thread_restrictions.h" |
[email protected] | 30039e6 | 2008-09-08 14:11:13 | [diff] [blame] | 45 | |
[email protected] | 6de0fd1d | 2011-11-15 13:31:49 | [diff] [blame] | 46 | // LazyInstance uses its own struct initializer-list style static |
Lei Zhang | 46df67b | 2017-09-05 21:54:09 | [diff] [blame] | 47 | // initialization, which does not require a constructor. |
[email protected] | 6de0fd1d | 2011-11-15 13:31:49 | [diff] [blame] | 48 | #define LAZY_INSTANCE_INITIALIZER {0} |
| 49 | |
[email protected] | 30039e6 | 2008-09-08 14:11:13 | [diff] [blame] | 50 | namespace base { |
| 51 | |
| 52 | template <typename Type> |
scottmg | 5e65e3a | 2017-03-08 08:48:46 | [diff] [blame] | 53 | struct LazyInstanceTraitsBase { |
[email protected] | c1aeaac | 2010-03-12 15:28:48 | [diff] [blame] | 54 | static Type* New(void* instance) { |
brettw | 16289b3e | 2017-06-13 21:58:40 | [diff] [blame] | 55 | DCHECK_EQ(reinterpret_cast<uintptr_t>(instance) & (alignof(Type) - 1), 0u); |
[email protected] | 30039e6 | 2008-09-08 14:11:13 | [diff] [blame] | 56 | // Use placement new to initialize our instance in our preallocated space. |
| 57 | // The parenthesis is very important here to force POD type initialization. |
[email protected] | c1aeaac | 2010-03-12 15:28:48 | [diff] [blame] | 58 | return new (instance) Type(); |
[email protected] | 30039e6 | 2008-09-08 14:11:13 | [diff] [blame] | 59 | } |
scottmg | 5e65e3a | 2017-03-08 08:48:46 | [diff] [blame] | 60 | |
| 61 | static void CallDestructor(Type* instance) { |
[email protected] | 30039e6 | 2008-09-08 14:11:13 | [diff] [blame] | 62 | // Explicitly call the destructor. |
[email protected] | 113eee0 | 2011-10-25 19:04:48 | [diff] [blame] | 63 | instance->~Type(); |
[email protected] | 30039e6 | 2008-09-08 14:11:13 | [diff] [blame] | 64 | } |
| 65 | }; |
| 66 | |
[email protected] | 67f92bc3 | 2012-01-26 01:56:19 | [diff] [blame] | 67 | // We pull out some of the functionality into non-templated functions, so we |
| 68 | // can implement the more complicated pieces out of line in the .cc file. |
| 69 | namespace internal { |
| 70 | |
scottmg | 5e65e3a | 2017-03-08 08:48:46 | [diff] [blame] | 71 | // This traits class causes destruction the contained Type at process exit via |
| 72 | // AtExitManager. This is probably generally not what you want. Instead, prefer |
| 73 | // Leaky below. |
| 74 | template <typename Type> |
| 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 | |
[email protected] | 9fc4416 | 2012-01-23 22:56:41 | [diff] [blame] | 90 | // Use LazyInstance<T>::Leaky for a less-verbose call-site typedef; e.g.: |
| 91 | // base::LazyInstance<T>::Leaky my_leaky_lazy_instance; |
| 92 | // instead of: |
[email protected] | 67f92bc3 | 2012-01-26 01:56:19 | [diff] [blame] | 93 | // base::LazyInstance<T, base::internal::LeakyLazyInstanceTraits<T> > |
| 94 | // my_leaky_lazy_instance; |
[email protected] | 9fc4416 | 2012-01-23 22:56:41 | [diff] [blame] | 95 | // (especially when T is MyLongTypeNameImplClientHolderFactory). |
[email protected] | 67f92bc3 | 2012-01-26 01:56:19 | [diff] [blame] | 96 | // Only use this internal::-qualified verbose form to extend this traits class |
| 97 | // (depending on its implementation details). |
[email protected] | dcc6933 | 2010-10-21 20:41:47 | [diff] [blame] | 98 | template <typename Type> |
| 99 | struct LeakyLazyInstanceTraits { |
[email protected] | 113eee0 | 2011-10-25 19:04:48 | [diff] [blame] | 100 | static const bool kRegisterOnExit = false; |
gab | 190f754 | 2016-08-01 20:03:41 | [diff] [blame] | 101 | #if DCHECK_IS_ON() |
[email protected] | 359d2bf | 2010-11-19 20:34:18 | [diff] [blame] | 102 | static const bool kAllowedToAccessOnNonjoinableThread = true; |
[email protected] | 5a8a806 | 2014-03-06 01:11:54 | [diff] [blame] | 103 | #endif |
[email protected] | 359d2bf | 2010-11-19 20:34:18 | [diff] [blame] | 104 | |
[email protected] | dcc6933 | 2010-10-21 20:41:47 | [diff] [blame] | 105 | static Type* New(void* instance) { |
[email protected] | b2206da5 | 2013-06-07 22:09:32 | [diff] [blame] | 106 | ANNOTATE_SCOPED_MEMORY_LEAK; |
scottmg | 5e65e3a | 2017-03-08 08:48:46 | [diff] [blame] | 107 | return LazyInstanceTraitsBase<Type>::New(instance); |
[email protected] | dcc6933 | 2010-10-21 20:41:47 | [diff] [blame] | 108 | } |
[email protected] | 113eee0 | 2011-10-25 19:04:48 | [diff] [blame] | 109 | static void Delete(Type* instance) { |
| 110 | } |
[email protected] | dcc6933 | 2010-10-21 20:41:47 | [diff] [blame] | 111 | }; |
| 112 | |
scottmg | 5e65e3a | 2017-03-08 08:48:46 | [diff] [blame] | 113 | template <typename Type> |
| 114 | struct ErrorMustSelectLazyOrDestructorAtExitForLazyInstance {}; |
| 115 | |
[email protected] | 6de0fd1d | 2011-11-15 13:31:49 | [diff] [blame] | 116 | // Our AtomicWord doubles as a spinlock, where a value of |
palmer | 84a608b | 2016-11-04 22:47:45 | [diff] [blame] | 117 | // kLazyInstanceStateCreating means the spinlock is being held for creation. |
Francois Doray | a50035b | 2017-06-12 17:55:50 | [diff] [blame] | 118 | constexpr subtle::AtomicWord kLazyInstanceStateCreating = 1; |
[email protected] | 1b651d5 | 2011-05-16 15:01:54 | [diff] [blame] | 119 | |
[email protected] | 6de0fd1d | 2011-11-15 13:31:49 | [diff] [blame] | 120 | // Check if instance needs to be created. If so return true otherwise |
| 121 | // if another thread has beat us, wait for instance to be created and |
| 122 | // return false. |
| 123 | BASE_EXPORT bool NeedsLazyInstance(subtle::AtomicWord* state); |
[email protected] | 30039e6 | 2008-09-08 14:11:13 | [diff] [blame] | 124 | |
[email protected] | 6de0fd1d | 2011-11-15 13:31:49 | [diff] [blame] | 125 | // After creating an instance, call this to register the dtor to be called |
| 126 | // at program exit and to update the atomic state to hold the |new_instance| |
| 127 | BASE_EXPORT void CompleteLazyInstance(subtle::AtomicWord* state, |
| 128 | subtle::AtomicWord new_instance, |
Francois Doray | a50035b | 2017-06-12 17:55:50 | [diff] [blame] | 129 | void (*destructor)(void*), |
| 130 | void* destructor_arg); |
| 131 | |
| 132 | // If |state| is uninitialized, constructs a value using |creator_func|, stores |
| 133 | // it into |state| and registers |destructor| to be called with |destructor_arg| |
| 134 | // as argument when the current AtExitManager goes out of scope. Then, returns |
| 135 | // the value stored in |state|. It is safe to have concurrent calls to this |
| 136 | // function with the same |state|. |
| 137 | template <typename CreatorFunc> |
| 138 | void* GetOrCreateLazyPointer(subtle::AtomicWord* state, |
| 139 | const CreatorFunc& creator_func, |
| 140 | void (*destructor)(void*), |
| 141 | void* destructor_arg) { |
| 142 | // If any bit in the created mask is true, the instance has already been |
| 143 | // fully constructed. |
| 144 | constexpr subtle::AtomicWord kLazyInstanceCreatedMask = |
| 145 | ~internal::kLazyInstanceStateCreating; |
| 146 | |
| 147 | // We will hopefully have fast access when the instance is already created. |
| 148 | // Since a thread sees |state| == 0 or kLazyInstanceStateCreating at most |
| 149 | // once, the load is taken out of NeedsLazyInstance() as a fast-path. The load |
| 150 | // has acquire memory ordering as a thread which sees |state| > creating needs |
| 151 | // to acquire visibility over the associated data. Pairing Release_Store is in |
| 152 | // CompleteLazyInstance(). |
| 153 | subtle::AtomicWord value = subtle::Acquire_Load(state); |
| 154 | if (!(value & kLazyInstanceCreatedMask) && NeedsLazyInstance(state)) { |
| 155 | // Create the instance in the space provided by |private_buf_|. |
| 156 | value = reinterpret_cast<subtle::AtomicWord>(creator_func()); |
| 157 | CompleteLazyInstance(state, value, destructor, destructor_arg); |
| 158 | } |
| 159 | return reinterpret_cast<void*>(subtle::NoBarrier_Load(state)); |
| 160 | } |
[email protected] | 1b651d5 | 2011-05-16 15:01:54 | [diff] [blame] | 161 | |
[email protected] | 6de0fd1d | 2011-11-15 13:31:49 | [diff] [blame] | 162 | } // namespace internal |
[email protected] | 30039e6 | 2008-09-08 14:11:13 | [diff] [blame] | 163 | |
scottmg | 5e65e3a | 2017-03-08 08:48:46 | [diff] [blame] | 164 | template < |
| 165 | typename Type, |
| 166 | typename Traits = |
| 167 | internal::ErrorMustSelectLazyOrDestructorAtExitForLazyInstance<Type>> |
[email protected] | 6de0fd1d | 2011-11-15 13:31:49 | [diff] [blame] | 168 | class LazyInstance { |
[email protected] | 30039e6 | 2008-09-08 14:11:13 | [diff] [blame] | 169 | public: |
[email protected] | 6de0fd1d | 2011-11-15 13:31:49 | [diff] [blame] | 170 | // Do not define a destructor, as doing so makes LazyInstance a |
| 171 | // non-POD-struct. We don't want that because then a static initializer will |
| 172 | // be created to register the (empty) destructor with atexit() under MSVC, for |
| 173 | // example. We handle destruction of the contained Type class explicitly via |
| 174 | // the OnExit member function, where needed. |
[email protected] | 1b651d5 | 2011-05-16 15:01:54 | [diff] [blame] | 175 | // ~LazyInstance() {} |
[email protected] | 30039e6 | 2008-09-08 14:11:13 | [diff] [blame] | 176 | |
[email protected] | 9fc4416 | 2012-01-23 22:56:41 | [diff] [blame] | 177 | // Convenience typedef to avoid having to repeat Type for leaky lazy |
| 178 | // instances. |
scottmg | 5e65e3a | 2017-03-08 08:48:46 | [diff] [blame] | 179 | typedef LazyInstance<Type, internal::LeakyLazyInstanceTraits<Type>> Leaky; |
| 180 | typedef LazyInstance<Type, internal::DestructorAtExitLazyInstanceTraits<Type>> |
| 181 | DestructorAtExit; |
[email protected] | 9fc4416 | 2012-01-23 22:56:41 | [diff] [blame] | 182 | |
[email protected] | 30039e6 | 2008-09-08 14:11:13 | [diff] [blame] | 183 | Type& Get() { |
| 184 | return *Pointer(); |
| 185 | } |
| 186 | |
| 187 | Type* Pointer() { |
gab | 190f754 | 2016-08-01 20:03:41 | [diff] [blame] | 188 | #if DCHECK_IS_ON() |
[email protected] | 3c7a7f3 | 2011-11-04 17:29:10 | [diff] [blame] | 189 | // Avoid making TLS lookup on release builds. |
[email protected] | 359d2bf | 2010-11-19 20:34:18 | [diff] [blame] | 190 | if (!Traits::kAllowedToAccessOnNonjoinableThread) |
[email protected] | 6de0fd1d | 2011-11-15 13:31:49 | [diff] [blame] | 191 | ThreadRestrictions::AssertSingletonAllowed(); |
[email protected] | 3c7a7f3 | 2011-11-04 17:29:10 | [diff] [blame] | 192 | #endif |
Francois Doray | a50035b | 2017-06-12 17:55:50 | [diff] [blame] | 193 | return static_cast<Type*>(internal::GetOrCreateLazyPointer( |
| 194 | &private_instance_, |
brettw | 16289b3e | 2017-06-13 21:58:40 | [diff] [blame] | 195 | [this]() { return Traits::New(private_buf_); }, |
Francois Doray | a50035b | 2017-06-12 17:55:50 | [diff] [blame] | 196 | Traits::kRegisterOnExit ? OnExit : nullptr, this)); |
[email protected] | 30039e6 | 2008-09-08 14:11:13 | [diff] [blame] | 197 | } |
| 198 | |
Lukasz Anforowicz | d3e1913 | 2017-12-06 19:44:27 | [diff] [blame^] | 199 | // Returns true if the lazy instance has been created. Unlike Get() and |
| 200 | // Pointer(), calling IsCreated() will not instantiate the object of Type. |
| 201 | bool IsCreated() { |
| 202 | // Return true (i.e. "created") if |private_instance_| is either being |
| 203 | // created right now (i.e. |private_instance_| has value of |
| 204 | // internal::kLazyInstanceStateCreating) or was already created (i.e. |
| 205 | // |private_instance_| has any other non-zero value). |
| 206 | return 0 != subtle::NoBarrier_Load(&private_instance_); |
[email protected] | 332710b | 2011-02-22 19:21:59 | [diff] [blame] | 207 | } |
| 208 | |
brettw | 16289b3e | 2017-06-13 21:58:40 | [diff] [blame] | 209 | // MSVC gives a warning that the alignment expands the size of the |
| 210 | // LazyInstance struct to make the size a multiple of the alignment. This |
| 211 | // is expected in this case. |
| 212 | #if defined(OS_WIN) |
| 213 | #pragma warning(push) |
| 214 | #pragma warning(disable: 4324) |
| 215 | #endif |
| 216 | |
[email protected] | 6de0fd1d | 2011-11-15 13:31:49 | [diff] [blame] | 217 | // Effectively private: member data is only public to allow the linker to |
[email protected] | cd924d6 | 2012-02-23 17:52:20 | [diff] [blame] | 218 | // statically initialize it and to maintain a POD class. DO NOT USE FROM |
| 219 | // OUTSIDE THIS CLASS. |
[email protected] | 6de0fd1d | 2011-11-15 13:31:49 | [diff] [blame] | 220 | subtle::AtomicWord private_instance_; |
brettw | 16289b3e | 2017-06-13 21:58:40 | [diff] [blame] | 221 | |
[email protected] | cd924d6 | 2012-02-23 17:52:20 | [diff] [blame] | 222 | // Preallocated space for the Type instance. |
brettw | 16289b3e | 2017-06-13 21:58:40 | [diff] [blame] | 223 | alignas(Type) char private_buf_[sizeof(Type)]; |
| 224 | |
| 225 | #if defined(OS_WIN) |
| 226 | #pragma warning(pop) |
| 227 | #endif |
[email protected] | 6de0fd1d | 2011-11-15 13:31:49 | [diff] [blame] | 228 | |
[email protected] | 30039e6 | 2008-09-08 14:11:13 | [diff] [blame] | 229 | private: |
[email protected] | 6de0fd1d | 2011-11-15 13:31:49 | [diff] [blame] | 230 | Type* instance() { |
| 231 | return reinterpret_cast<Type*>(subtle::NoBarrier_Load(&private_instance_)); |
| 232 | } |
| 233 | |
[email protected] | 625332e0 | 2010-12-14 07:48:49 | [diff] [blame] | 234 | // Adapter function for use with AtExit. This should be called single |
[email protected] | 113eee0 | 2011-10-25 19:04:48 | [diff] [blame] | 235 | // threaded, so don't synchronize across threads. |
[email protected] | 625332e0 | 2010-12-14 07:48:49 | [diff] [blame] | 236 | // Calling OnExit while the instance is in use by other threads is a mistake. |
| 237 | static void OnExit(void* lazy_instance) { |
| 238 | LazyInstance<Type, Traits>* me = |
| 239 | reinterpret_cast<LazyInstance<Type, Traits>*>(lazy_instance); |
[email protected] | 6de0fd1d | 2011-11-15 13:31:49 | [diff] [blame] | 240 | Traits::Delete(me->instance()); |
[email protected] | cd924d6 | 2012-02-23 17:52:20 | [diff] [blame] | 241 | subtle::NoBarrier_Store(&me->private_instance_, 0); |
[email protected] | 625332e0 | 2010-12-14 07:48:49 | [diff] [blame] | 242 | } |
[email protected] | 30039e6 | 2008-09-08 14:11:13 | [diff] [blame] | 243 | }; |
| 244 | |
| 245 | } // namespace base |
| 246 | |
| 247 | #endif // BASE_LAZY_INSTANCE_H_ |