OLD | NEW |
---|---|
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 // 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 base::LinkerInitialized constructor. | 17 // a global variable using the base::LinkerInitialized constructor. |
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(base::LINKER_INITIALIZED); | 27 // static LazyInstance<MyClass> my_instance = LINKER_ZERO_INITIALIZED; |
Nico
2011/11/11 20:21:56
Is this needed? Aren't statics implicitly zero ini
joth
2011/11/14 16:58:23
Just needed as a double check to prove to the call
| |
28 // void SomeMethod() { | 28 // void SomeMethod() { |
29 // my_instance.Get().SomeMethod(); // MyClass::SomeMethod() | 29 // my_instance.Get().SomeMethod(); // MyClass::SomeMethod() |
30 // | 30 // |
31 // MyClass* ptr = my_instance.Pointer(); | 31 // MyClass* ptr = my_instance.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 #pragma once | 37 #pragma once |
(...skipping 34 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... | |
72 static const bool kRegisterOnExit = false; | 72 static const bool kRegisterOnExit = false; |
73 static const bool kAllowedToAccessOnNonjoinableThread = true; | 73 static const bool kAllowedToAccessOnNonjoinableThread = true; |
74 | 74 |
75 static Type* New(void* instance) { | 75 static Type* New(void* instance) { |
76 return DefaultLazyInstanceTraits<Type>::New(instance); | 76 return DefaultLazyInstanceTraits<Type>::New(instance); |
77 } | 77 } |
78 static void Delete(Type* instance) { | 78 static void Delete(Type* instance) { |
79 } | 79 } |
80 }; | 80 }; |
81 | 81 |
82 // We pull out some of the functionality into a non-templated base, so that we | 82 // We pull out some of the functionality into a non-templated functions, so we |
83 // can implement the more complicated pieces out of line in the .cc file. | 83 // we can implement the more complicated pieces out of line in the .cc file. |
84 class BASE_EXPORT LazyInstanceHelper { | 84 namespace internal { |
85 protected: | |
86 enum { | |
87 STATE_EMPTY = 0, | |
88 STATE_CREATING = 1, | |
89 STATE_CREATED = 2 | |
90 }; | |
91 | 85 |
92 explicit LazyInstanceHelper(LinkerInitialized /*unused*/) {/* state_ is 0 */} | 86 // Our AtomicWord doubles as a spinlock, where a value of |
87 // kBeingCreatedMarker means the spinlock is being held for creation. | |
88 static const subtle::AtomicWord kLazyInstanceStateCreating = 1; | |
93 | 89 |
90 // Declaring a destructor (even if it's empty) will cause MSVC to register a | |
91 // static initializer to register the empty destructor with atexit(). | |
92 | |
93 // Check if instance needs to be created. If so return true otherwise | |
94 // if another thread has beat us, wait for instance to be created and | |
95 // return false. | |
96 BASE_EXPORT bool NeedsLazyInstance(base::subtle::AtomicWord* state); | |
97 | |
98 // After creating an instance, call this to register the dtor to be called | |
99 // at program exit and to update the atomic state to hold the |new_instance| | |
100 BASE_EXPORT void CompleteLazyInstance(base::subtle::AtomicWord* state, | |
101 base::subtle::AtomicWord new_instance, | |
102 void* lazy_instance, | |
103 void (*dtor)(void*)); | |
104 | |
105 } // namespace internal | |
106 | |
107 #define LINKER_ZERO_INITIALIZED {0} | |
108 | |
109 template <typename Type, typename Traits = DefaultLazyInstanceTraits<Type> > | |
110 class LazyInstance { | |
111 public: | |
94 // Declaring a destructor (even if it's empty) will cause MSVC to register a | 112 // Declaring a destructor (even if it's empty) will cause MSVC to register a |
95 // static initializer to register the empty destructor with atexit(). | 113 // static initializer to register the empty destructor with atexit(). |
96 | |
97 // A destructor is intentionally not defined. If we were to say | |
98 // ~LazyInstanceHelper() { } | |
99 // Even though it's empty, a destructor will still be generated. | 114 // Even though it's empty, a destructor will still be generated. |
100 // In order for the constructor to be called for static variables, | 115 // In order for the constructor to be called for static variables, |
101 // it will be registered as a callback at runtime with AtExit(). | 116 // it will be registered as a callback at runtime with AtExit(). |
102 // We don't want this, so we don't declare a destructor at all, | 117 // We don't want this, so we don't declare a destructor at all, |
103 // effectively keeping the type POD (at least in terms of | 118 // effectively keeping the type POD (at least in terms of |
104 // initialization and destruction). | 119 // initialization and destruction). |
105 | |
106 // Check if instance needs to be created. If so return true otherwise | |
107 // if another thread has beat us, wait for instance to be created and | |
108 // return false. | |
109 bool NeedsInstance(); | |
110 | |
111 // After creating an instance, call this to register the dtor to be called | |
112 // at program exit and to update the state to STATE_CREATED. | |
113 void CompleteInstance(void* instance, void (*dtor)(void*)); | |
114 | |
115 base::subtle::Atomic32 state_; | |
116 | |
117 private: | |
118 DISALLOW_COPY_AND_ASSIGN(LazyInstanceHelper); | |
119 }; | |
120 | |
121 template <typename Type, typename Traits = DefaultLazyInstanceTraits<Type> > | |
122 class LazyInstance : public LazyInstanceHelper { | |
123 public: | |
124 explicit LazyInstance(LinkerInitialized x) : LazyInstanceHelper(x) { } | |
125 | |
126 // Declaring a destructor (even if it's empty) will cause MSVC to register a | |
127 // static initializer to register the empty destructor with atexit(). | |
128 // Refer to the destructor-related comment in LazyInstanceHelper. | |
129 // ~LazyInstance() {} | 120 // ~LazyInstance() {} |
130 | 121 |
131 Type& Get() { | 122 Type& Get() { |
132 return *Pointer(); | 123 return *Pointer(); |
133 } | 124 } |
134 | 125 |
135 Type* Pointer() { | 126 Type* Pointer() { |
136 #ifndef NDEBUG | 127 #ifndef NDEBUG |
137 // Avoid making TLS lookup on release builds. | 128 // Avoid making TLS lookup on release builds. |
138 if (!Traits::kAllowedToAccessOnNonjoinableThread) | 129 if (!Traits::kAllowedToAccessOnNonjoinableThread) |
139 base::ThreadRestrictions::AssertSingletonAllowed(); | 130 base::ThreadRestrictions::AssertSingletonAllowed(); |
140 #endif | 131 #endif |
141 | 132 |
142 // We will hopefully have fast access when the instance is already created. | 133 // We will hopefully have fast access when the instance is already created. |
143 // Since a thread sees state_ != STATE_CREATED at most once, | 134 // Since a thread sees private_instance_ == 0 or Creating at most once, |
willchan no longer on Chromium
2011/11/11 22:18:21
You mean kLazyInstanceStateCreating instead of jus
joth
2011/11/14 16:58:23
Done.
| |
144 // the load is taken out of NeedsInstance() as a fast-path. | 135 // the load is taken out of NeedsInstance() as a fast-path. |
145 // The load has acquire memory ordering as a thread which sees | 136 // The load has acquire memory ordering as a thread which sees |
146 // state_ == STATE_CREATED needs to acquire visibility over | 137 // private_instance_ > creating needs to acquire visibility over |
147 // the associated data (buf_). Pairing Release_Store is in | 138 // the associated data (private_buf_). Pairing Release_Store is in |
148 // CompleteInstance(). | 139 // CompleteInstance(). |
149 if ((base::subtle::Acquire_Load(&state_) != STATE_CREATED) && | 140 base::subtle::AtomicWord value = |
willchan no longer on Chromium
2011/11/11 22:18:21
No need to use base:: from within the base namespa
joth
2011/11/14 16:58:23
Done. here & many other places in .h and .cc
| |
150 NeedsInstance()) { | 141 base::subtle::Acquire_Load(&private_instance_); |
151 // Create the instance in the space provided by |buf_|. | 142 if ((value == 0 || value == internal::kLazyInstanceStateCreating) && |
willchan no longer on Chromium
2011/11/11 22:18:21
I'm not sure I understand why we changed away from
joth
2011/11/14 16:58:23
Yep memory reduction plus consistency with Singlet
| |
152 instance_ = Traits::New(buf_); | 143 internal::NeedsLazyInstance(&private_instance_)) { |
153 CompleteInstance(this, Traits::kRegisterOnExit ? OnExit : NULL); | 144 // Create the instance in the space provided by |private_buf_|. |
145 value = reinterpret_cast<base::subtle::AtomicWord>( | |
146 Traits::New(private_buf_)); | |
147 internal::CompleteLazyInstance(&private_instance_, value, this, | |
148 Traits::kRegisterOnExit ? OnExit : NULL); | |
154 } | 149 } |
155 | 150 |
156 // This annotation helps race detectors recognize correct lock-less | 151 // This annotation helps race detectors recognize correct lock-less |
157 // synchronization between different threads calling Pointer(). | 152 // synchronization between different threads calling Pointer(). |
158 // We suggest dynamic race detection tool that "Traits::New" above | 153 // We suggest dynamic race detection tool that "Traits::New" above |
159 // and CompleteInstance(...) happens before "return instance_" below. | 154 // and CompleteInstance(...) happens before "return instance()" below. |
160 // See the corresponding HAPPENS_BEFORE in CompleteInstance(...). | 155 // See the corresponding HAPPENS_BEFORE in CompleteInstance(...). |
161 ANNOTATE_HAPPENS_AFTER(&state_); | 156 ANNOTATE_HAPPENS_AFTER(&private_instance_); |
162 return instance_; | 157 return instance(); |
163 } | 158 } |
164 | 159 |
165 bool operator==(Type* p) { | 160 bool operator==(Type* p) { |
166 switch (base::subtle::NoBarrier_Load(&state_)) { | 161 switch (base::subtle::NoBarrier_Load(&private_instance_)) { |
167 case STATE_EMPTY: | 162 case 0: |
168 return p == NULL; | 163 return p == NULL; |
169 case STATE_CREATING: | 164 case internal::kLazyInstanceStateCreating: |
170 return static_cast<int8*>(static_cast<void*>(p)) == buf_; | 165 return static_cast<int8*>(static_cast<void*>(p)) == private_buf_; |
171 case STATE_CREATED: | |
172 return p == instance_; | |
173 default: | 166 default: |
174 return false; | 167 return p == instance(); |
175 } | 168 } |
176 } | 169 } |
177 | 170 |
171 // Effectively private: member data is only public to allow the linker to | |
Nico
2011/11/11 20:21:56
Sentence cut off
joth
2011/11/11 21:15:36
Done.
| |
172 // Note this must use AtomicWord, not Atomic32, to ensure correct alignment of | |
173 // |private_buf_| on 64 bit arcchitectures. | |
Nico
2011/11/11 20:21:56
spello arcchitectures
joth
2011/11/11 21:15:36
Done.
| |
174 base::subtle::AtomicWord private_instance_; | |
175 // statically initialize it. DO NOT USE FROM OUTSIDE THIS CLASS. | |
176 int8 private_buf_[sizeof(Type)]; // Preallocated space for the Type instance. | |
177 | |
178 private: | 178 private: |
179 Type* instance() { return reinterpret_cast<Type*>(private_instance_); } | |
180 | |
179 // Adapter function for use with AtExit. This should be called single | 181 // Adapter function for use with AtExit. This should be called single |
180 // threaded, so don't synchronize across threads. | 182 // threaded, so don't synchronize across threads. |
181 // Calling OnExit while the instance is in use by other threads is a mistake. | 183 // Calling OnExit while the instance is in use by other threads is a mistake. |
182 static void OnExit(void* lazy_instance) { | 184 static void OnExit(void* lazy_instance) { |
183 LazyInstance<Type, Traits>* me = | 185 LazyInstance<Type, Traits>* me = |
184 reinterpret_cast<LazyInstance<Type, Traits>*>(lazy_instance); | 186 reinterpret_cast<LazyInstance<Type, Traits>*>(lazy_instance); |
185 Traits::Delete(me->instance_); | 187 Traits::Delete(me->instance()); |
186 me->instance_ = NULL; | 188 base::subtle::Release_Store(&me->private_instance_, 0); |
187 base::subtle::Release_Store(&me->state_, STATE_EMPTY); | |
188 } | 189 } |
189 | |
190 Type *instance_; | |
191 int8 buf_[sizeof(Type)]; // Preallocate the space for the Type instance. | |
192 | |
193 DISALLOW_COPY_AND_ASSIGN(LazyInstance); | |
194 }; | 190 }; |
195 | 191 |
196 } // namespace base | 192 } // namespace base |
197 | 193 |
198 #endif // BASE_LAZY_INSTANCE_H_ | 194 #endif // BASE_LAZY_INSTANCE_H_ |
OLD | NEW |