singleton.h 10 KB

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