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

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: willchan 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
« no previous file with comments | « base/i18n/number_formatting.cc ('k') | base/lazy_instance.cc » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
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 (notably gcc 4.4) this still ends up needing runtime
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 // Check if instance needs to be created. If so return true otherwise
95 // static initializer to register the empty destructor with atexit(). 97 // if another thread has beat us, wait for instance to be created and
98 // return false.
99 BASE_EXPORT bool NeedsLazyInstance(subtle::AtomicWord* state);
96 100
97 // A destructor is intentionally not defined. If we were to say 101 // After creating an instance, call this to register the dtor to be called
98 // ~LazyInstanceHelper() { } 102 // at program exit and to update the atomic state to hold the |new_instance|
99 // Even though it's empty, a destructor will still be generated. 103 BASE_EXPORT void CompleteLazyInstance(subtle::AtomicWord* state,
100 // In order for the constructor to be called for static variables, 104 subtle::AtomicWord new_instance,
101 // it will be registered as a callback at runtime with AtExit(). 105 void* lazy_instance,
102 // We don't want this, so we don't declare a destructor at all, 106 void (*dtor)(void*));
103 // effectively keeping the type POD (at least in terms of
104 // initialization and destruction).
105 107
106 // Check if instance needs to be created. If so return true otherwise 108 } // namespace internal
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 109
121 template <typename Type, typename Traits = DefaultLazyInstanceTraits<Type> > 110 template <typename Type, typename Traits = DefaultLazyInstanceTraits<Type> >
122 class LazyInstance : public LazyInstanceHelper { 111 class LazyInstance {
123 public: 112 public:
124 explicit LazyInstance(LinkerInitialized x) : LazyInstanceHelper(x) { } 113 // Do not define a destructor, as doing so makes LazyInstance a
125 114 // 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 115 // be created to register the (empty) destructor with atexit() under MSVC, for
127 // static initializer to register the empty destructor with atexit(). 116 // example. We handle destruction of the contained Type class explicitly via
128 // Refer to the destructor-related comment in LazyInstanceHelper. 117 // the OnExit member function, where needed.
129 // ~LazyInstance() {} 118 // ~LazyInstance() {}
130 119
131 Type& Get() { 120 Type& Get() {
132 return *Pointer(); 121 return *Pointer();
133 } 122 }
134 123
135 Type* Pointer() { 124 Type* Pointer() {
136 #ifndef NDEBUG 125 #ifndef NDEBUG
137 // Avoid making TLS lookup on release builds. 126 // Avoid making TLS lookup on release builds.
138 if (!Traits::kAllowedToAccessOnNonjoinableThread) 127 if (!Traits::kAllowedToAccessOnNonjoinableThread)
139 base::ThreadRestrictions::AssertSingletonAllowed(); 128 ThreadRestrictions::AssertSingletonAllowed();
140 #endif 129 #endif
130 // If any bit in the created mask is true, the instance has already been
131 // fully constructed.
132 static const subtle::AtomicWord kLazyInstanceCreatedMask =
133 ~internal::kLazyInstanceStateCreating;
141 134
142 // We will hopefully have fast access when the instance is already created. 135 // We will hopefully have fast access when the instance is already created.
143 // Since a thread sees state_ != STATE_CREATED at most once, 136 // Since a thread sees private_instance_ == 0 or kLazyInstanceStateCreating
144 // the load is taken out of NeedsInstance() as a fast-path. 137 // 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 138 // The load has acquire memory ordering as a thread which sees
146 // state_ == STATE_CREATED needs to acquire visibility over 139 // private_instance_ > creating needs to acquire visibility over
147 // the associated data (buf_). Pairing Release_Store is in 140 // the associated data (private_buf_). Pairing Release_Store is in
148 // CompleteInstance(). 141 // CompleteLazyInstance().
149 if ((base::subtle::Acquire_Load(&state_) != STATE_CREATED) && 142 subtle::AtomicWord value = subtle::Acquire_Load(&private_instance_);
150 NeedsInstance()) { 143 if (!(value & kLazyInstanceCreatedMask) &&
151 // Create the instance in the space provided by |buf_|. 144 internal::NeedsLazyInstance(&private_instance_)) {
152 instance_ = Traits::New(buf_); 145 // Create the instance in the space provided by |private_buf_|.
153 CompleteInstance(this, Traits::kRegisterOnExit ? OnExit : NULL); 146 value = reinterpret_cast<subtle::AtomicWord>(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 CompleteLazyInstance(...) happens before "return instance()" below.
160 // See the corresponding HAPPENS_BEFORE in CompleteInstance(...). 155 // See the corresponding HAPPENS_BEFORE in CompleteLazyInstance(...).
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 (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
172 // statically initialize it. DO NOT USE FROM OUTSIDE THIS CLASS.
173
174 // Note this must use AtomicWord, not Atomic32, to ensure correct alignment
175 // of |private_buf_| on 64 bit architectures. (This member must be first to
176 // allow the syntax used in LAZY_INSTANCE_INITIALIZER to work correctly.)
177 subtle::AtomicWord private_instance_;
178 int8 private_buf_[sizeof(Type)]; // Preallocated space for the Type instance.
179
178 private: 180 private:
181 Type* instance() { return reinterpret_cast<Type*>(private_instance_); }
182
179 // Adapter function for use with AtExit. This should be called single 183 // Adapter function for use with AtExit. This should be called single
180 // threaded, so don't synchronize across threads. 184 // threaded, so don't synchronize across threads.
181 // Calling OnExit while the instance is in use by other threads is a mistake. 185 // Calling OnExit while the instance is in use by other threads is a mistake.
182 static void OnExit(void* lazy_instance) { 186 static void OnExit(void* lazy_instance) {
183 LazyInstance<Type, Traits>* me = 187 LazyInstance<Type, Traits>* me =
184 reinterpret_cast<LazyInstance<Type, Traits>*>(lazy_instance); 188 reinterpret_cast<LazyInstance<Type, Traits>*>(lazy_instance);
185 Traits::Delete(me->instance_); 189 Traits::Delete(me->instance());
186 me->instance_ = NULL; 190 subtle::Release_Store(&me->private_instance_, 0);
187 base::subtle::Release_Store(&me->state_, STATE_EMPTY);
188 } 191 }
189
190 Type *instance_;
191 int8 buf_[sizeof(Type)]; // Preallocate the space for the Type instance.
192
193 DISALLOW_COPY_AND_ASSIGN(LazyInstance);
194 }; 192 };
195 193
196 } // namespace base 194 } // namespace base
197 195
198 #endif // BASE_LAZY_INSTANCE_H_ 196 #endif // BASE_LAZY_INSTANCE_H_
OLDNEW
« no previous file with comments | « base/i18n/number_formatting.cc ('k') | base/lazy_instance.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698