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

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: thakis comment, renamed LAZY_INSTANCE_INITIALIZER 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 it's on sruct initializer-list style static initialization,
M-A Ruel 2011/11/11 21:34:06 struct
Mark Mentovai 2011/11/11 21:38:08 Marc-Antoine Ruel wrote:
joth 2011/11/14 16:58:23 Done.
joth 2011/11/14 16:58:23 Done. // LazyInstance uses its own struct initiali
49 // as base's LINKER_INITIALIZED requires a constructor and on some compilers
50 // (noteably gcc 4.6) this still ends up needing runtime initialization.
51 #define LAZY_INSTANCE_INITIALIZER {0}
grt (UTC plus 2) 2011/11/12 02:45:17 Would changing {0} to {} allow you to make the dat
joth 2011/11/14 16:58:23 No, all data members must still be public, and AIU
grt (UTC plus 2) 2011/11/14 17:54:25 Ah, I see my mistake: if the class has non-public
52
48 namespace base { 53 namespace base {
49 54
50 template <typename Type> 55 template <typename Type>
51 struct DefaultLazyInstanceTraits { 56 struct DefaultLazyInstanceTraits {
52 static const bool kRegisterOnExit = true; 57 static const bool kRegisterOnExit = true;
53 static const bool kAllowedToAccessOnNonjoinableThread = false; 58 static const bool kAllowedToAccessOnNonjoinableThread = false;
54 59
55 static Type* New(void* instance) { 60 static Type* New(void* instance) {
56 DCHECK_EQ(reinterpret_cast<uintptr_t>(instance) % sizeof(instance), 0u) 61 DCHECK_EQ(reinterpret_cast<uintptr_t>(instance) % sizeof(instance), 0u)
57 << ": Bad boy, the buffer passed to placement new is not aligned!\n" 62 << ": Bad boy, the buffer passed to placement new is not aligned!\n"
(...skipping 14 matching lines...) Expand all
72 static const bool kRegisterOnExit = false; 77 static const bool kRegisterOnExit = false;
73 static const bool kAllowedToAccessOnNonjoinableThread = true; 78 static const bool kAllowedToAccessOnNonjoinableThread = true;
74 79
75 static Type* New(void* instance) { 80 static Type* New(void* instance) {
76 return DefaultLazyInstanceTraits<Type>::New(instance); 81 return DefaultLazyInstanceTraits<Type>::New(instance);
77 } 82 }
78 static void Delete(Type* instance) { 83 static void Delete(Type* instance) {
79 } 84 }
80 }; 85 };
81 86
82 // We pull out some of the functionality into a non-templated base, so that we 87 // We pull out some of the functionality into a non-templated functions, so we
grt (UTC plus 2) 2011/11/12 02:45:17 "into non-templated functions"
joth 2011/11/14 16:58:23 Done.
83 // can implement the more complicated pieces out of line in the .cc file. 88 // we can implement the more complicated pieces out of line in the .cc file.
grt (UTC plus 2) 2011/11/12 02:45:17 "we we" -> "we"
joth 2011/11/14 16:58:23 Done.
84 class BASE_EXPORT LazyInstanceHelper { 89 namespace internal {
85 protected:
86 enum {
87 STATE_EMPTY = 0,
88 STATE_CREATING = 1,
89 STATE_CREATED = 2
90 };
91 90
92 explicit LazyInstanceHelper(LinkerInitialized /*unused*/) {/* state_ is 0 */} 91 // Our AtomicWord doubles as a spinlock, where a value of
92 // kBeingCreatedMarker means the spinlock is being held for creation.
93 static const subtle::AtomicWord kLazyInstanceStateCreating = 1;
93 94
95 // Declaring a destructor (even if it's empty) will cause MSVC to register a
grt (UTC plus 2) 2011/11/12 02:45:17 This seems out of place.
joth 2011/11/14 16:58:23 Done.
96 // static initializer to register the empty destructor with atexit().
97
98 // Check if instance needs to be created. If so return true otherwise
99 // if another thread has beat us, wait for instance to be created and
100 // return false.
101 BASE_EXPORT bool NeedsLazyInstance(base::subtle::AtomicWord* state);
102
103 // After creating an instance, call this to register the dtor to be called
104 // at program exit and to update the atomic state to hold the |new_instance|
105 BASE_EXPORT void CompleteLazyInstance(base::subtle::AtomicWord* state,
106 base::subtle::AtomicWord new_instance,
107 void* lazy_instance,
108 void (*dtor)(void*));
109
110 } // namespace internal
111
112 template <typename Type, typename Traits = DefaultLazyInstanceTraits<Type> >
113 class LazyInstance {
114 public:
94 // Declaring a destructor (even if it's empty) will cause MSVC to register a 115 // Declaring a destructor (even if it's empty) will cause MSVC to register a
grt (UTC plus 2) 2011/11/12 02:45:17 I realize you didn't add this comment, but it bugs
joth 2011/11/14 16:58:23 Done-ish. I wrote a compromise version, LMKWYT:
grt (UTC plus 2) 2011/11/14 17:54:25 SGTM
95 // static initializer to register the empty destructor with atexit(). 116 // 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. 117 // Even though it's empty, a destructor will still be generated.
100 // In order for the constructor to be called for static variables, 118 // In order for the constructor to be called for static variables,
101 // it will be registered as a callback at runtime with AtExit(). 119 // 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, 120 // 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 121 // effectively keeping the type POD (at least in terms of
104 // initialization and destruction). 122 // 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() {} 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 base::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 Creating at most once,
144 // the load is taken out of NeedsInstance() as a fast-path. 138 // 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().
149 if ((base::subtle::Acquire_Load(&state_) != STATE_CREATED) && 143 base::subtle::AtomicWord value =
150 NeedsInstance()) { 144 base::subtle::Acquire_Load(&private_instance_);
151 // Create the instance in the space provided by |buf_|. 145 if ((value == 0 || value == internal::kLazyInstanceStateCreating) &&
152 instance_ = Traits::New(buf_); 146 internal::NeedsLazyInstance(&private_instance_)) {
153 CompleteInstance(this, Traits::kRegisterOnExit ? OnExit : NULL); 147 // Create the instance in the space provided by |private_buf_|.
148 value = reinterpret_cast<base::subtle::AtomicWord>(
149 Traits::New(private_buf_));
150 internal::CompleteLazyInstance(&private_instance_, value, this,
151 Traits::kRegisterOnExit ? OnExit : NULL);
154 } 152 }
155 153
156 // This annotation helps race detectors recognize correct lock-less 154 // This annotation helps race detectors recognize correct lock-less
157 // synchronization between different threads calling Pointer(). 155 // synchronization between different threads calling Pointer().
158 // We suggest dynamic race detection tool that "Traits::New" above 156 // We suggest dynamic race detection tool that "Traits::New" above
159 // and CompleteInstance(...) happens before "return instance_" below. 157 // and CompleteInstance(...) happens before "return instance()" below.
160 // See the corresponding HAPPENS_BEFORE in CompleteInstance(...). 158 // See the corresponding HAPPENS_BEFORE in CompleteInstance(...).
161 ANNOTATE_HAPPENS_AFTER(&state_); 159 ANNOTATE_HAPPENS_AFTER(&private_instance_);
162 return instance_; 160 return instance();
163 } 161 }
164 162
165 bool operator==(Type* p) { 163 bool operator==(Type* p) {
166 switch (base::subtle::NoBarrier_Load(&state_)) { 164 switch (base::subtle::NoBarrier_Load(&private_instance_)) {
167 case STATE_EMPTY: 165 case 0:
168 return p == NULL; 166 return p == NULL;
169 case STATE_CREATING: 167 case internal::kLazyInstanceStateCreating:
170 return static_cast<int8*>(static_cast<void*>(p)) == buf_; 168 return static_cast<int8*>(static_cast<void*>(p)) == private_buf_;
171 case STATE_CREATED:
172 return p == instance_;
173 default: 169 default:
174 return false; 170 return p == instance();
175 } 171 }
176 } 172 }
177 173
174 // Effectively private: member data is only public to allow the linker to
175 // statically initialize it. DO NOT USE FROM OUTSIDE THIS CLASS.
176
177 // Note this must use AtomicWord, not Atomic32, to ensure correct alignment
178 // of |private_buf_| on 64 bit architectures. (This member must be first to
179 // allow the syntax used in LAZY_INSTANCE_INITIALIZER to work correctly.)
180 base::subtle::AtomicWord private_instance_;
181 int8 private_buf_[sizeof(Type)]; // Preallocated space for the Type instance.
182
178 private: 183 private:
184 Type* instance() { return reinterpret_cast<Type*>(private_instance_); }
185
179 // Adapter function for use with AtExit. This should be called single 186 // Adapter function for use with AtExit. This should be called single
180 // threaded, so don't synchronize across threads. 187 // threaded, so don't synchronize across threads.
181 // Calling OnExit while the instance is in use by other threads is a mistake. 188 // Calling OnExit while the instance is in use by other threads is a mistake.
182 static void OnExit(void* lazy_instance) { 189 static void OnExit(void* lazy_instance) {
183 LazyInstance<Type, Traits>* me = 190 LazyInstance<Type, Traits>* me =
184 reinterpret_cast<LazyInstance<Type, Traits>*>(lazy_instance); 191 reinterpret_cast<LazyInstance<Type, Traits>*>(lazy_instance);
185 Traits::Delete(me->instance_); 192 Traits::Delete(me->instance());
186 me->instance_ = NULL; 193 base::subtle::Release_Store(&me->private_instance_, 0);
187 base::subtle::Release_Store(&me->state_, STATE_EMPTY);
188 } 194 }
189
190 Type *instance_;
191 int8 buf_[sizeof(Type)]; // Preallocate the space for the Type instance.
192
193 DISALLOW_COPY_AND_ASSIGN(LazyInstance);
194 }; 195 };
195 196
196 } // namespace base 197 } // namespace base
197 198
198 #endif // BASE_LAZY_INSTANCE_H_ 199 #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