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

Side by Side Diff: base/lazy_instance.h

Issue 1039823002: Add base::LazyInstance (Closed) Base URL: https://chromium.googlesource.com/chromium/mini_chromium@master
Patch Set: Created 5 years, 9 months 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
« no previous file with comments | « base/compiler_specific.h ('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
(Empty)
1 // Copyright 2008 The Chromium Authors. All rights reserved.
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 //
12 // LazyInstance is completely thread safe, assuming that you create it safely.
13 // The class was designed to be POD initialized, so it shouldn't require a
14 // static constructor. It really only makes sense to declare a LazyInstance as
15 // a global variable using the LAZY_INSTANCE_INITIALIZER initializer.
16 //
17 // LazyInstance is similar to Singleton, except it does not have the singleton
18 // property. You can have multiple LazyInstance's of the same type, and each
19 // will manage a unique instance. It also preallocates the space for Type, as
20 // to avoid allocating the Type instance on the heap. This may help with the
21 // performance of creating the instance, and reducing heap fragmentation. This
22 // requires that Type be a complete type so we can determine the size.
23 //
24 // Example usage:
25 // static LazyInstance<MyClass> my_instance = LAZY_INSTANCE_INITIALIZER;
26 // void SomeMethod() {
27 // my_instance.Get().SomeMethod(); // MyClass::SomeMethod()
28 //
29 // MyClass* ptr = my_instance.Pointer();
30 // ptr->DoDoDo(); // MyClass::DoDoDo
31 // }
32
33 #ifndef MINI_CHROMIUM_BASE_LAZY_INSTANCE_H_
34 #define MINI_CHROMIUM_BASE_LAZY_INSTANCE_H_
35
36 #include <new>
37
38 #include "base/atomicops.h"
39 #include "base/basictypes.h"
40 #include "base/logging.h"
41 #include "base/memory/aligned_memory.h"
42
43 // LazyInstance uses its own struct initializer-list style static
44 // initialization, as base's LINKER_INITIALIZED requires a constructor and on
45 // some compilers (notably gcc 4.4) this still ends up needing runtime
46 // initialization.
47 #define LAZY_INSTANCE_INITIALIZER {0}
48
49 namespace base {
50
51 template <typename Type>
52 struct DefaultLazyInstanceTraits {
53 // mini_chromium does not support Traits::kRegisterOnExit = true because it
54 // does not provide AtExitManager. Only LeakyLazyInstanceTraits is supported.
55 static const bool kRegisterOnExit = true;
56
57 static Type* New(void* instance) {
58 DCHECK_EQ(reinterpret_cast<uintptr_t>(instance) & (ALIGNOF(Type) - 1), 0u);
59 // Use placement new to initialize our instance in our preallocated space.
60 // The parenthesis is very important here to force POD type initialization.
61 return new (instance) Type();
62 }
63 static void Delete(Type* instance) {
64 // Explicitly call the destructor.
65 instance->~Type();
66 }
67 };
68
69 // We pull out some of the functionality into non-templated functions, so we
70 // can implement the more complicated pieces out of line in the .cc file.
71 namespace internal {
72
73 // Use LazyInstance<T>::Leaky for a less-verbose call-site typedef; e.g.:
74 // base::LazyInstance<T>::Leaky my_leaky_lazy_instance;
75 // instead of:
76 // base::LazyInstance<T, base::internal::LeakyLazyInstanceTraits<T> >
77 // my_leaky_lazy_instance;
78 // (especially when T is MyLongTypeNameImplClientHolderFactory).
79 // Only use this internal::-qualified verbose form to extend this traits class
80 // (depending on its implementation details).
81 template <typename Type>
82 struct LeakyLazyInstanceTraits {
83 static const bool kRegisterOnExit = false;
84
85 static Type* New(void* instance) {
86 return DefaultLazyInstanceTraits<Type>::New(instance);
87 }
88 static void Delete(Type* instance) {
89 }
90 };
91
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;
95
96 // Check if instance needs to be created. If so return true otherwise
97 // if another thread has beat us, wait for instance to be created and
98 // return false.
99 bool NeedsLazyInstance(subtle::AtomicWord* state);
100
101 // After creating an instance, call this to register the dtor to be called
102 // at program exit and to update the atomic state to hold the |new_instance|
103 void CompleteLazyInstance(subtle::AtomicWord* state,
104 subtle::AtomicWord new_instance,
105 void* lazy_instance);
106
107 } // namespace internal
108
109 template <typename Type, typename Traits = DefaultLazyInstanceTraits<Type> >
110 class LazyInstance {
111 public:
112 // Do not define a destructor, as doing so makes LazyInstance a
113 // non-POD-struct. We don't want that because then a static initializer will
114 // be created to register the (empty) destructor with atexit() under MSVC, for
115 // example.
116 // ~LazyInstance() {}
117
118 // Convenience typedef to avoid having to repeat Type for leaky lazy
119 // instances.
120 typedef LazyInstance<Type, internal::LeakyLazyInstanceTraits<Type> > Leaky;
121
122 Type& Get() {
123 return *Pointer();
124 }
125
126 Type* Pointer() {
127 // If any bit in the created mask is true, the instance has already been
128 // fully constructed.
129 static const subtle::AtomicWord kLazyInstanceCreatedMask =
130 ~internal::kLazyInstanceStateCreating;
131
132 // We will hopefully have fast access when the instance is already created.
133 // Since a thread sees private_instance_ == 0 or kLazyInstanceStateCreating
134 // at most once, the load is taken out of NeedsInstance() as a fast-path.
135 // The load has acquire memory ordering as a thread which sees
136 // private_instance_ > creating needs to acquire visibility over
137 // the associated data (private_buf_). Pairing Release_Store is in
138 // CompleteLazyInstance().
139 subtle::AtomicWord value = subtle::Acquire_Load(&private_instance_);
140 if (!(value & kLazyInstanceCreatedMask) &&
141 internal::NeedsLazyInstance(&private_instance_)) {
142 // Create the instance in the space provided by |private_buf_|.
143 value = reinterpret_cast<subtle::AtomicWord>(
144 Traits::New(private_buf_.void_data()));
145 internal::CompleteLazyInstance(&private_instance_, value, this);
146
147 // mini_chromium does not support Traits::kRegisterOnExit = true because
148 // it does not provide AtExitManager. Instead of LazyInstanceTraits, use
149 // LeakyLazyInstanceTraits, and note that destructors will not run.
150 static_assert(!Traits::kRegisterOnExit,
151 "destruction not supported in mini_chromium");
152 }
153 return instance();
154 }
155
156 bool operator==(Type* p) {
157 switch (subtle::NoBarrier_Load(&private_instance_)) {
158 case 0:
159 return p == NULL;
160 case internal::kLazyInstanceStateCreating:
161 return static_cast<void*>(p) == private_buf_.void_data();
162 default:
163 return p == instance();
164 }
165 }
166
167 // Effectively private: member data is only public to allow the linker to
168 // statically initialize it and to maintain a POD class. DO NOT USE FROM
169 // OUTSIDE THIS CLASS.
170
171 subtle::AtomicWord private_instance_;
172 // Preallocated space for the Type instance.
173 base::AlignedMemory<sizeof(Type), ALIGNOF(Type)> private_buf_;
174
175 private:
176 Type* instance() {
177 return reinterpret_cast<Type*>(subtle::NoBarrier_Load(&private_instance_));
178 }
179 };
180
181 } // namespace base
182
183 #endif // MINI_CHROMIUM_BASE_LAZY_INSTANCE_H_
OLDNEW
« no previous file with comments | « base/compiler_specific.h ('k') | base/lazy_instance.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698