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

Side by Side Diff: base/lazy_instance.h

Issue 8491043: Allow linker initialization of lazy instance (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: review comments + rebase Created 9 years, 1 month 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 | Annotate | Revision Log
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 // 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 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(base::LINKER_INITIALIZED); 27 // static LazyInstance<MyClass> my_instance = LAZY_INSTANCE_INITIALIZER;
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
38 38
39 #include <new> // For placement new. 39 #include <new> // For placement new.
40 40
41 #include "base/atomicops.h" 41 #include "base/atomicops.h"
42 #include "base/base_export.h" 42 #include "base/base_export.h"
43 #include "base/basictypes.h" 43 #include "base/basictypes.h"
44 #include "base/logging.h" 44 #include "base/logging.h"
45 #include "base/third_party/dynamic_annotations/dynamic_annotations.h" 45 #include "base/third_party/dynamic_annotations/dynamic_annotations.h"
46 #include "base/threading/thread_restrictions.h" 46 #include "base/threading/thread_restrictions.h"
47 47
48 // LazyInstance uses its own struct initializer-list style static
49 // initialization, as base's LINKER_INITIALIZED requires a constructor and on
50 // some compilers (noteably gcc 4.4) this still ends up needing runtime
willchan no longer on Chromium 2011/11/14 17:29:06 notably
joth 2011/11/15 11:40:41 Done.
51 // initialization.
52 #define LAZY_INSTANCE_INITIALIZER {0}
53
48 namespace base { 54 namespace base {
49 55
50 template <typename Type> 56 template <typename Type>
51 struct DefaultLazyInstanceTraits { 57 struct DefaultLazyInstanceTraits {
52 static const bool kRegisterOnExit = true; 58 static const bool kRegisterOnExit = true;
53 static const bool kAllowedToAccessOnNonjoinableThread = false; 59 static const bool kAllowedToAccessOnNonjoinableThread = false;
54 60
55 static Type* New(void* instance) { 61 static Type* New(void* instance) {
56 DCHECK_EQ(reinterpret_cast<uintptr_t>(instance) % sizeof(instance), 0u) 62 DCHECK_EQ(reinterpret_cast<uintptr_t>(instance) % sizeof(instance), 0u)
57 << ": Bad boy, the buffer passed to placement new is not aligned!\n" 63 << ": Bad boy, the buffer passed to placement new is not aligned!\n"
(...skipping 14 matching lines...) Expand all
72 static const bool kRegisterOnExit = false; 78 static const bool kRegisterOnExit = false;
73 static const bool kAllowedToAccessOnNonjoinableThread = true; 79 static const bool kAllowedToAccessOnNonjoinableThread = true;
74 80
75 static Type* New(void* instance) { 81 static Type* New(void* instance) {
76 return DefaultLazyInstanceTraits<Type>::New(instance); 82 return DefaultLazyInstanceTraits<Type>::New(instance);
77 } 83 }
78 static void Delete(Type* instance) { 84 static void Delete(Type* instance) {
79 } 85 }
80 }; 86 };
81 87
82 // We pull out some of the functionality into a non-templated base, so that we 88 // We pull out some of the functionality into non-templated functions, so we
83 // can implement the more complicated pieces out of line in the .cc file. 89 // can implement the more complicated pieces out of line in the .cc file.
84 class BASE_EXPORT LazyInstanceHelper { 90 namespace internal {
85 protected:
86 enum {
87 STATE_EMPTY = 0,
88 STATE_CREATING = 1,
89 STATE_CREATED = 2
90 };
91 91
92 explicit LazyInstanceHelper(LinkerInitialized /*unused*/) {/* state_ is 0 */} 92 // Our AtomicWord doubles as a spinlock, where a value of
93 // kBeingCreatedMarker means the spinlock is being held for creation.
94 static const subtle::AtomicWord kLazyInstanceStateCreating = 1;
93 95
94 // Declaring a destructor (even if it's empty) will cause MSVC to register a 96 // If any bit in the created mask is true, the instance has already been fully
95 // static initializer to register the empty destructor with atexit(). 97 // constructed. This is defined as a convenience.
98 static const subtle::AtomicWord kLazyInstanceCreatedMask =
willchan no longer on Chromium 2011/11/14 17:29:06 This probably can be scoped to the function, right
joth 2011/11/15 11:40:41 Done.
99 ~kLazyInstanceStateCreating;
96 100
97 // A destructor is intentionally not defined. If we were to say 101 // Check if instance needs to be created. If so return true otherwise
98 // ~LazyInstanceHelper() { } 102 // if another thread has beat us, wait for instance to be created and
99 // Even though it's empty, a destructor will still be generated. 103 // return false.
100 // In order for the constructor to be called for static variables, 104 BASE_EXPORT bool NeedsLazyInstance(subtle::AtomicWord* state);
101 // 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,
103 // effectively keeping the type POD (at least in terms of
104 // initialization and destruction).
105 105
106 // Check if instance needs to be created. If so return true otherwise 106 // After creating an instance, call this to register the dtor to be called
107 // if another thread has beat us, wait for instance to be created and 107 // at program exit and to update the atomic state to hold the |new_instance|
108 // return false. 108 BASE_EXPORT void CompleteLazyInstance(subtle::AtomicWord* state,
109 bool NeedsInstance(); 109 subtle::AtomicWord new_instance,
110 void* lazy_instance,
111 void (*dtor)(void*));
110 112
111 // After creating an instance, call this to register the dtor to be called 113 } // namespace internal
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 114
121 template <typename Type, typename Traits = DefaultLazyInstanceTraits<Type> > 115 template <typename Type, typename Traits = DefaultLazyInstanceTraits<Type> >
122 class LazyInstance : public LazyInstanceHelper { 116 class LazyInstance {
123 public: 117 public:
124 explicit LazyInstance(LinkerInitialized x) : LazyInstanceHelper(x) { } 118 // Do not define a destructor, as doing so makes LazyInstance a
125 119 // non-POD-struct. We don't want that because then a static initializer will
126 // Declaring a destructor (even if it's empty) will cause MSVC to register a 120 // be created to register the (empty) destructor with atexit() under MSVC, for
127 // static initializer to register the empty destructor with atexit(). 121 // example. We handle destruction of the contained Type class explicitly via
128 // Refer to the destructor-related comment in LazyInstanceHelper. 122 // the OnExit member function, where needed.
129 // ~LazyInstance() {} 123 // ~LazyInstance() {}
130 124
131 Type& Get() { 125 Type& Get() {
132 return *Pointer(); 126 return *Pointer();
133 } 127 }
134 128
135 Type* Pointer() { 129 Type* Pointer() {
136 #ifndef NDEBUG 130 #ifndef NDEBUG
137 // Avoid making TLS lookup on release builds. 131 // Avoid making TLS lookup on release builds.
138 if (!Traits::kAllowedToAccessOnNonjoinableThread) 132 if (!Traits::kAllowedToAccessOnNonjoinableThread)
139 base::ThreadRestrictions::AssertSingletonAllowed(); 133 ThreadRestrictions::AssertSingletonAllowed();
140 #endif 134 #endif
141 135
142 // We will hopefully have fast access when the instance is already created. 136 // We will hopefully have fast access when the instance is already created.
143 // Since a thread sees state_ != STATE_CREATED at most once, 137 // Since a thread sees private_instance_ == 0 or kLazyInstanceStateCreating
144 // the load is taken out of NeedsInstance() as a fast-path. 138 // at most once, the load is taken out of NeedsInstance() as a fast-path.
145 // The load has acquire memory ordering as a thread which sees 139 // The load has acquire memory ordering as a thread which sees
146 // state_ == STATE_CREATED needs to acquire visibility over 140 // private_instance_ > creating needs to acquire visibility over
147 // the associated data (buf_). Pairing Release_Store is in 141 // the associated data (private_buf_). Pairing Release_Store is in
148 // CompleteInstance(). 142 // CompleteInstance().
willchan no longer on Chromium 2011/11/14 17:29:06 s/CompleteInstance/CompleteLazyInstance/
joth 2011/11/15 11:40:41 Done.
149 if ((base::subtle::Acquire_Load(&state_) != STATE_CREATED) && 143 subtle::AtomicWord value = subtle::Acquire_Load(&private_instance_);
150 NeedsInstance()) { 144 if (!(value & internal::kLazyInstanceCreatedMask) &&
151 // Create the instance in the space provided by |buf_|. 145 internal::NeedsLazyInstance(&private_instance_)) {
152 instance_ = Traits::New(buf_); 146 // Create the instance in the space provided by |private_buf_|.
153 CompleteInstance(this, Traits::kRegisterOnExit ? OnExit : NULL); 147 value = reinterpret_cast<subtle::AtomicWord>(Traits::New(private_buf_));
148 internal::CompleteLazyInstance(&private_instance_, value, this,
149 Traits::kRegisterOnExit ? OnExit : NULL);
154 } 150 }
155 151
156 // This annotation helps race detectors recognize correct lock-less 152 // This annotation helps race detectors recognize correct lock-less
157 // synchronization between different threads calling Pointer(). 153 // synchronization between different threads calling Pointer().
158 // We suggest dynamic race detection tool that "Traits::New" above 154 // We suggest dynamic race detection tool that "Traits::New" above
159 // and CompleteInstance(...) happens before "return instance_" below. 155 // and CompleteInstance(...) happens before "return instance()" below.
160 // See the corresponding HAPPENS_BEFORE in CompleteInstance(...). 156 // See the corresponding HAPPENS_BEFORE in CompleteInstance(...).
161 ANNOTATE_HAPPENS_AFTER(&state_); 157 ANNOTATE_HAPPENS_AFTER(&private_instance_);
162 return instance_; 158 return instance();
163 } 159 }
164 160
165 bool operator==(Type* p) { 161 bool operator==(Type* p) {
166 switch (base::subtle::NoBarrier_Load(&state_)) { 162 switch (subtle::NoBarrier_Load(&private_instance_)) {
167 case STATE_EMPTY: 163 case 0:
168 return p == NULL; 164 return p == NULL;
169 case STATE_CREATING: 165 case internal::kLazyInstanceStateCreating:
170 return static_cast<int8*>(static_cast<void*>(p)) == buf_; 166 return static_cast<int8*>(static_cast<void*>(p)) == private_buf_;
171 case STATE_CREATED:
172 return p == instance_;
173 default: 167 default:
174 return false; 168 return p == instance();
175 } 169 }
176 } 170 }
177 171
172 // Effectively private: member data is only public to allow the linker to
173 // statically initialize it. DO NOT USE FROM OUTSIDE THIS CLASS.
174
175 // Note this must use AtomicWord, not Atomic32, to ensure correct alignment
176 // of |private_buf_| on 64 bit architectures. (This member must be first to
177 // allow the syntax used in LAZY_INSTANCE_INITIALIZER to work correctly.)
178 subtle::AtomicWord private_instance_;
179 int8 private_buf_[sizeof(Type)]; // Preallocated space for the Type instance.
180
178 private: 181 private:
182 Type* instance() { return reinterpret_cast<Type*>(private_instance_); }
183
179 // Adapter function for use with AtExit. This should be called single 184 // Adapter function for use with AtExit. This should be called single
180 // threaded, so don't synchronize across threads. 185 // threaded, so don't synchronize across threads.
181 // Calling OnExit while the instance is in use by other threads is a mistake. 186 // Calling OnExit while the instance is in use by other threads is a mistake.
182 static void OnExit(void* lazy_instance) { 187 static void OnExit(void* lazy_instance) {
183 LazyInstance<Type, Traits>* me = 188 LazyInstance<Type, Traits>* me =
184 reinterpret_cast<LazyInstance<Type, Traits>*>(lazy_instance); 189 reinterpret_cast<LazyInstance<Type, Traits>*>(lazy_instance);
185 Traits::Delete(me->instance_); 190 Traits::Delete(me->instance());
186 me->instance_ = NULL; 191 subtle::Release_Store(&me->private_instance_, 0);
187 base::subtle::Release_Store(&me->state_, STATE_EMPTY);
188 } 192 }
189
190 Type *instance_;
191 int8 buf_[sizeof(Type)]; // Preallocate the space for the Type instance.
192
193 DISALLOW_COPY_AND_ASSIGN(LazyInstance);
194 }; 193 };
195 194
196 } // namespace base 195 } // namespace base
197 196
198 #endif // BASE_LAZY_INSTANCE_H_ 197 #endif // BASE_LAZY_INSTANCE_H_
OLDNEW
« no previous file with comments | « base/i18n/number_formatting.cc ('k') | base/lazy_instance.cc » ('j') | base/lazy_instance.cc » ('J')

Powered by Google App Engine
This is Rietveld 408576698