singleton.h 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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
  3. // found in the LICENSE file.
  4. //
  5. // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  6. // PLEASE READ: Do you really need a singleton? If possible, use a
  7. // function-local static of type base::NoDestructor<T> instead:
  8. //
  9. // Factory& Factory::GetInstance() {
  10. // static base::NoDestructor<Factory> instance;
  11. // return *instance;
  12. // }
  13. // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  14. //
  15. // Singletons make it hard to determine the lifetime of an object, which can
  16. // lead to buggy code and spurious crashes.
  17. //
  18. // Instead of adding another singleton into the mix, try to identify either:
  19. // a) An existing singleton that can manage your object's lifetime
  20. // b) Locations where you can deterministically create the object and pass
  21. // into other objects
  22. //
  23. // If you absolutely need a singleton, please keep them as trivial as possible
  24. // and ideally a leaf dependency. Singletons get problematic when they attempt
  25. // to do too much in their destructor or have circular dependencies.
  26. #ifndef BASE_MEMORY_SINGLETON_H_
  27. #define BASE_MEMORY_SINGLETON_H_
  28. #include "base/at_exit.h"
  29. #include "base/atomicops.h"
  30. #include "base/base_export.h"
  31. #include "base/check_op.h"
  32. #include "base/lazy_instance_helpers.h"
  33. #include "base/macros.h"
  34. #include "base/threading/thread_restrictions.h"
  35. namespace base {
  36. // Default traits for Singleton<Type>. Calls operator new and operator delete on
  37. // the object. Registers automatic deletion at process exit.
  38. // Overload if you need arguments or another memory allocation function.
  39. template<typename Type>
  40. struct DefaultSingletonTraits {
  41. // Allocates the object.
  42. static Type* New() {
  43. // The parenthesis is very important here; it forces POD type
  44. // initialization.
  45. return new Type();
  46. }
  47. // Destroys the object.
  48. static void Delete(Type* x) {
  49. delete x;
  50. }
  51. // Set to true to automatically register deletion of the object on process
  52. // exit. See below for the required call that makes this happen.
  53. static const bool kRegisterAtExit = true;
  54. #if DCHECK_IS_ON()
  55. // Set to false to disallow access on a non-joinable thread. This is
  56. // different from kRegisterAtExit because StaticMemorySingletonTraits allows
  57. // access on non-joinable threads, and gracefully handles this.
  58. static const bool kAllowedToAccessOnNonjoinableThread = false;
  59. #endif
  60. };
  61. // Alternate traits for use with the Singleton<Type>. Identical to
  62. // DefaultSingletonTraits except that the Singleton will not be cleaned up
  63. // at exit.
  64. template<typename Type>
  65. struct LeakySingletonTraits : public DefaultSingletonTraits<Type> {
  66. static const bool kRegisterAtExit = false;
  67. #if DCHECK_IS_ON()
  68. static const bool kAllowedToAccessOnNonjoinableThread = true;
  69. #endif
  70. };
  71. // Alternate traits for use with the Singleton<Type>. Allocates memory
  72. // for the singleton instance from a static buffer. The singleton will
  73. // be cleaned up at exit, but can't be revived after destruction unless
  74. // the ResurrectForTesting() method is called.
  75. //
  76. // This is useful for a certain category of things, notably logging and
  77. // tracing, where the singleton instance is of a type carefully constructed to
  78. // be safe to access post-destruction.
  79. // In logging and tracing you'll typically get stray calls at odd times, like
  80. // during static destruction, thread teardown and the like, and there's a
  81. // termination race on the heap-based singleton - e.g. if one thread calls
  82. // get(), but then another thread initiates AtExit processing, the first thread
  83. // may call into an object residing in unallocated memory. If the instance is
  84. // allocated from the data segment, then this is survivable.
  85. //
  86. // The destructor is to deallocate system resources, in this case to unregister
  87. // a callback the system will invoke when logging levels change. Note that
  88. // this is also used in e.g. Chrome Frame, where you have to allow for the
  89. // possibility of loading briefly into someone else's process space, and
  90. // so leaking is not an option, as that would sabotage the state of your host
  91. // process once you've unloaded.
  92. template <typename Type>
  93. struct StaticMemorySingletonTraits {
  94. // WARNING: User has to support a New() which returns null.
  95. static Type* New() {
  96. // Only constructs once and returns pointer; otherwise returns null.
  97. if (subtle::NoBarrier_AtomicExchange(&dead_, 1))
  98. return nullptr;
  99. return new (buffer_) Type();
  100. }
  101. static void Delete(Type* p) {
  102. if (p)
  103. p->Type::~Type();
  104. }
  105. static const bool kRegisterAtExit = true;
  106. #if DCHECK_IS_ON()
  107. static const bool kAllowedToAccessOnNonjoinableThread = true;
  108. #endif
  109. static void ResurrectForTesting() { subtle::NoBarrier_Store(&dead_, 0); }
  110. private:
  111. alignas(Type) static char buffer_[sizeof(Type)];
  112. // Signal the object was already deleted, so it is not revived.
  113. static subtle::Atomic32 dead_;
  114. };
  115. template <typename Type>
  116. alignas(Type) char StaticMemorySingletonTraits<Type>::buffer_[sizeof(Type)];
  117. template <typename Type>
  118. subtle::Atomic32 StaticMemorySingletonTraits<Type>::dead_ = 0;
  119. // The Singleton<Type, Traits, DifferentiatingType> class manages a single
  120. // instance of Type which will be created on first use and will be destroyed at
  121. // normal process exit). The Trait::Delete function will not be called on
  122. // abnormal process exit.
  123. //
  124. // DifferentiatingType is used as a key to differentiate two different
  125. // singletons having the same memory allocation functions but serving a
  126. // different purpose. This is mainly used for Locks serving different purposes.
  127. //
  128. // Example usage:
  129. //
  130. // In your header:
  131. // namespace base {
  132. // template <typename T>
  133. // struct DefaultSingletonTraits;
  134. // }
  135. // class FooClass {
  136. // public:
  137. // static FooClass* GetInstance(); <-- See comment below on this.
  138. // void Bar() { ... }
  139. // private:
  140. // FooClass() { ... }
  141. // friend struct base::DefaultSingletonTraits<FooClass>;
  142. //
  143. // DISALLOW_COPY_AND_ASSIGN(FooClass);
  144. // };
  145. //
  146. // In your source file:
  147. // #include "base/memory/singleton.h"
  148. // FooClass* FooClass::GetInstance() {
  149. // return base::Singleton<FooClass>::get();
  150. // }
  151. //
  152. // Or for leaky singletons:
  153. // #include "base/memory/singleton.h"
  154. // FooClass* FooClass::GetInstance() {
  155. // return base::Singleton<
  156. // FooClass, base::LeakySingletonTraits<FooClass>>::get();
  157. // }
  158. //
  159. // And to call methods on FooClass:
  160. // FooClass::GetInstance()->Bar();
  161. //
  162. // NOTE: The method accessing Singleton<T>::get() has to be named as GetInstance
  163. // and it is important that FooClass::GetInstance() is not inlined in the
  164. // header. This makes sure that when source files from multiple targets include
  165. // this header they don't end up with different copies of the inlined code
  166. // creating multiple copies of the singleton.
  167. //
  168. // Singleton<> has no non-static members and doesn't need to actually be
  169. // instantiated.
  170. //
  171. // This class is itself thread-safe. The underlying Type must of course be
  172. // thread-safe if you want to use it concurrently. Two parameters may be tuned
  173. // depending on the user's requirements.
  174. //
  175. // Glossary:
  176. // RAE = kRegisterAtExit
  177. //
  178. // On every platform, if Traits::RAE is true, the singleton will be destroyed at
  179. // process exit. More precisely it uses AtExitManager which requires an
  180. // object of this type to be instantiated. AtExitManager mimics the semantics
  181. // of atexit() such as LIFO order but under Windows is safer to call. For more
  182. // information see at_exit.h.
  183. //
  184. // If Traits::RAE is false, the singleton will not be freed at process exit,
  185. // thus the singleton will be leaked if it is ever accessed. Traits::RAE
  186. // shouldn't be false unless absolutely necessary. Remember that the heap where
  187. // the object is allocated may be destroyed by the CRT anyway.
  188. //
  189. // Caveats:
  190. // (a) Every call to get(), operator->() and operator*() incurs some overhead
  191. // (16ns on my P4/2.8GHz) to check whether the object has already been
  192. // initialized. You may wish to cache the result of get(); it will not
  193. // change.
  194. //
  195. // (b) Your factory function must never throw an exception. This class is not
  196. // exception-safe.
  197. //
  198. template <typename Type,
  199. typename Traits = DefaultSingletonTraits<Type>,
  200. typename DifferentiatingType = Type>
  201. class Singleton {
  202. private:
  203. // A class T using the Singleton<T> pattern should declare a GetInstance()
  204. // method and call Singleton::get() from within that. T may also declare a
  205. // GetInstanceIfExists() method to invoke Singleton::GetIfExists().
  206. friend Type;
  207. // This class is safe to be constructed and copy-constructed since it has no
  208. // member.
  209. // Returns a pointer to the one true instance of the class.
  210. static Type* get() {
  211. #if DCHECK_IS_ON()
  212. if (!Traits::kAllowedToAccessOnNonjoinableThread)
  213. ThreadRestrictions::AssertSingletonAllowed();
  214. #endif
  215. return subtle::GetOrCreateLazyPointer(
  216. &instance_, &CreatorFunc, nullptr,
  217. Traits::kRegisterAtExit ? OnExit : nullptr, nullptr);
  218. }
  219. // Returns the same result as get() if the instance exists but doesn't
  220. // construct it (and returns null) if it doesn't.
  221. static Type* GetIfExists() {
  222. #if DCHECK_IS_ON()
  223. if (!Traits::kAllowedToAccessOnNonjoinableThread)
  224. ThreadRestrictions::AssertSingletonAllowed();
  225. #endif
  226. if (!subtle::NoBarrier_Load(&instance_))
  227. return nullptr;
  228. // Need to invoke get() nonetheless as some Traits return null after
  229. // destruction (even though |instance_| still holds garbage).
  230. return get();
  231. }
  232. // Internal method used as an adaptor for GetOrCreateLazyPointer(). Do not use
  233. // outside of that use case.
  234. static Type* CreatorFunc(void* /* creator_arg*/) { return Traits::New(); }
  235. // Adapter function for use with AtExit(). This should be called single
  236. // threaded, so don't use atomic operations.
  237. // Calling OnExit while singleton is in use by other threads is a mistake.
  238. static void OnExit(void* /*unused*/) {
  239. // AtExit should only ever be register after the singleton instance was
  240. // created. We should only ever get here with a valid instance_ pointer.
  241. Traits::Delete(reinterpret_cast<Type*>(subtle::NoBarrier_Load(&instance_)));
  242. instance_ = 0;
  243. }
  244. static subtle::AtomicWord instance_;
  245. };
  246. template <typename Type, typename Traits, typename DifferentiatingType>
  247. subtle::AtomicWord Singleton<Type, Traits, DifferentiatingType>::instance_ = 0;
  248. } // namespace base
  249. #endif // BASE_MEMORY_SINGLETON_H_