michael@0: // Copyright (c) 2012 The Chromium Authors. All rights reserved. michael@0: // Use of this source code is governed by a BSD-style license that can be michael@0: // found in the LICENSE file. michael@0: michael@0: // The LazyInstance class manages a single instance of Type, michael@0: // which will be lazily created on the first time it's accessed. This class is michael@0: // useful for places you would normally use a function-level static, but you michael@0: // need to have guaranteed thread-safety. The Type constructor will only ever michael@0: // be called once, even if two threads are racing to create the object. Get() michael@0: // and Pointer() will always return the same, completely initialized instance. michael@0: // When the instance is constructed it is registered with AtExitManager. The michael@0: // destructor will be called on program exit. michael@0: // michael@0: // LazyInstance is completely thread safe, assuming that you create it safely. michael@0: // The class was designed to be POD initialized, so it shouldn't require a michael@0: // static constructor. It really only makes sense to declare a LazyInstance as michael@0: // a global variable using the LAZY_INSTANCE_INITIALIZER initializer. michael@0: // michael@0: // LazyInstance is similar to Singleton, except it does not have the singleton michael@0: // property. You can have multiple LazyInstance's of the same type, and each michael@0: // will manage a unique instance. It also preallocates the space for Type, as michael@0: // to avoid allocating the Type instance on the heap. This may help with the michael@0: // performance of creating the instance, and reducing heap fragmentation. This michael@0: // requires that Type be a complete type so we can determine the size. michael@0: // michael@0: // Example usage: michael@0: // static LazyInstance my_instance = LAZY_INSTANCE_INITIALIZER; michael@0: // void SomeMethod() { michael@0: // my_instance.Get().SomeMethod(); // MyClass::SomeMethod() michael@0: // michael@0: // MyClass* ptr = my_instance.Pointer(); michael@0: // ptr->DoDoDo(); // MyClass::DoDoDo michael@0: // } michael@0: michael@0: #ifndef BASE_LAZY_INSTANCE_H_ michael@0: #define BASE_LAZY_INSTANCE_H_ michael@0: michael@0: #include // For placement new. michael@0: michael@0: #include "base/atomicops.h" michael@0: #include "base/base_export.h" michael@0: #include "base/basictypes.h" michael@0: #include "base/debug/leak_annotations.h" michael@0: #include "base/logging.h" michael@0: #include "base/memory/aligned_memory.h" michael@0: #include "base/third_party/dynamic_annotations/dynamic_annotations.h" michael@0: #include "base/threading/thread_restrictions.h" michael@0: michael@0: // LazyInstance uses its own struct initializer-list style static michael@0: // initialization, as base's LINKER_INITIALIZED requires a constructor and on michael@0: // some compilers (notably gcc 4.4) this still ends up needing runtime michael@0: // initialization. michael@0: #define LAZY_INSTANCE_INITIALIZER {0} michael@0: michael@0: namespace base { michael@0: michael@0: template michael@0: struct DefaultLazyInstanceTraits { michael@0: static const bool kRegisterOnExit = true; michael@0: static const bool kAllowedToAccessOnNonjoinableThread = false; michael@0: michael@0: static Type* New(void* instance) { michael@0: DCHECK_EQ(reinterpret_cast(instance) & (ALIGNOF(Type) - 1), 0u) michael@0: << ": Bad boy, the buffer passed to placement new is not aligned!\n" michael@0: "This may break some stuff like SSE-based optimizations assuming the " michael@0: " objects are word aligned."; michael@0: // Use placement new to initialize our instance in our preallocated space. michael@0: // The parenthesis is very important here to force POD type initialization. michael@0: return new (instance) Type(); michael@0: } michael@0: static void Delete(Type* instance) { michael@0: // Explicitly call the destructor. michael@0: instance->~Type(); michael@0: } michael@0: }; michael@0: michael@0: // We pull out some of the functionality into non-templated functions, so we michael@0: // can implement the more complicated pieces out of line in the .cc file. michael@0: namespace internal { michael@0: michael@0: // Use LazyInstance::Leaky for a less-verbose call-site typedef; e.g.: michael@0: // base::LazyInstance::Leaky my_leaky_lazy_instance; michael@0: // instead of: michael@0: // base::LazyInstance > michael@0: // my_leaky_lazy_instance; michael@0: // (especially when T is MyLongTypeNameImplClientHolderFactory). michael@0: // Only use this internal::-qualified verbose form to extend this traits class michael@0: // (depending on its implementation details). michael@0: template michael@0: struct LeakyLazyInstanceTraits { michael@0: static const bool kRegisterOnExit = false; michael@0: static const bool kAllowedToAccessOnNonjoinableThread = true; michael@0: michael@0: static Type* New(void* instance) { michael@0: ANNOTATE_SCOPED_MEMORY_LEAK; michael@0: return DefaultLazyInstanceTraits::New(instance); michael@0: } michael@0: static void Delete(Type* instance) { michael@0: } michael@0: }; michael@0: michael@0: // Our AtomicWord doubles as a spinlock, where a value of michael@0: // kBeingCreatedMarker means the spinlock is being held for creation. michael@0: static const subtle::AtomicWord kLazyInstanceStateCreating = 1; michael@0: michael@0: // Check if instance needs to be created. If so return true otherwise michael@0: // if another thread has beat us, wait for instance to be created and michael@0: // return false. michael@0: BASE_EXPORT bool NeedsLazyInstance(subtle::AtomicWord* state); michael@0: michael@0: // After creating an instance, call this to register the dtor to be called michael@0: // at program exit and to update the atomic state to hold the |new_instance| michael@0: BASE_EXPORT void CompleteLazyInstance(subtle::AtomicWord* state, michael@0: subtle::AtomicWord new_instance, michael@0: void* lazy_instance, michael@0: void (*dtor)(void*)); michael@0: michael@0: } // namespace internal michael@0: michael@0: template > michael@0: class LazyInstance { michael@0: public: michael@0: // Do not define a destructor, as doing so makes LazyInstance a michael@0: // non-POD-struct. We don't want that because then a static initializer will michael@0: // be created to register the (empty) destructor with atexit() under MSVC, for michael@0: // example. We handle destruction of the contained Type class explicitly via michael@0: // the OnExit member function, where needed. michael@0: // ~LazyInstance() {} michael@0: michael@0: // Convenience typedef to avoid having to repeat Type for leaky lazy michael@0: // instances. michael@0: typedef LazyInstance > Leaky; michael@0: michael@0: Type& Get() { michael@0: return *Pointer(); michael@0: } michael@0: michael@0: Type* Pointer() { michael@0: #ifndef NDEBUG michael@0: // Avoid making TLS lookup on release builds. michael@0: if (!Traits::kAllowedToAccessOnNonjoinableThread) michael@0: ThreadRestrictions::AssertSingletonAllowed(); michael@0: #endif michael@0: // If any bit in the created mask is true, the instance has already been michael@0: // fully constructed. michael@0: static const subtle::AtomicWord kLazyInstanceCreatedMask = michael@0: ~internal::kLazyInstanceStateCreating; michael@0: michael@0: // We will hopefully have fast access when the instance is already created. michael@0: // Since a thread sees private_instance_ == 0 or kLazyInstanceStateCreating michael@0: // at most once, the load is taken out of NeedsInstance() as a fast-path. michael@0: // The load has acquire memory ordering as a thread which sees michael@0: // private_instance_ > creating needs to acquire visibility over michael@0: // the associated data (private_buf_). Pairing Release_Store is in michael@0: // CompleteLazyInstance(). michael@0: subtle::AtomicWord value = subtle::Acquire_Load(&private_instance_); michael@0: if (!(value & kLazyInstanceCreatedMask) && michael@0: internal::NeedsLazyInstance(&private_instance_)) { michael@0: // Create the instance in the space provided by |private_buf_|. michael@0: value = reinterpret_cast( michael@0: Traits::New(private_buf_.void_data())); michael@0: internal::CompleteLazyInstance(&private_instance_, value, this, michael@0: Traits::kRegisterOnExit ? OnExit : NULL); michael@0: } michael@0: michael@0: // This annotation helps race detectors recognize correct lock-less michael@0: // synchronization between different threads calling Pointer(). michael@0: // We suggest dynamic race detection tool that "Traits::New" above michael@0: // and CompleteLazyInstance(...) happens before "return instance()" below. michael@0: // See the corresponding HAPPENS_BEFORE in CompleteLazyInstance(...). michael@0: ANNOTATE_HAPPENS_AFTER(&private_instance_); michael@0: return instance(); michael@0: } michael@0: michael@0: bool operator==(Type* p) { michael@0: switch (subtle::NoBarrier_Load(&private_instance_)) { michael@0: case 0: michael@0: return p == NULL; michael@0: case internal::kLazyInstanceStateCreating: michael@0: return static_cast(p) == private_buf_.void_data(); michael@0: default: michael@0: return p == instance(); michael@0: } michael@0: } michael@0: michael@0: // Effectively private: member data is only public to allow the linker to michael@0: // statically initialize it and to maintain a POD class. DO NOT USE FROM michael@0: // OUTSIDE THIS CLASS. michael@0: michael@0: subtle::AtomicWord private_instance_; michael@0: // Preallocated space for the Type instance. michael@0: base::AlignedMemory private_buf_; michael@0: michael@0: private: michael@0: Type* instance() { michael@0: return reinterpret_cast(subtle::NoBarrier_Load(&private_instance_)); michael@0: } michael@0: michael@0: // Adapter function for use with AtExit. This should be called single michael@0: // threaded, so don't synchronize across threads. michael@0: // Calling OnExit while the instance is in use by other threads is a mistake. michael@0: static void OnExit(void* lazy_instance) { michael@0: LazyInstance* me = michael@0: reinterpret_cast*>(lazy_instance); michael@0: Traits::Delete(me->instance()); michael@0: subtle::NoBarrier_Store(&me->private_instance_, 0); michael@0: } michael@0: }; michael@0: michael@0: } // namespace base michael@0: michael@0: #endif // BASE_LAZY_INSTANCE_H_