llsingleton.h 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. /**
  2. * @file llsingleton.h
  3. *
  4. * $LicenseInfo:firstyear=2002&license=viewergpl$
  5. *
  6. * Copyright (c) 2010, Linden Research, Inc.
  7. *
  8. * Second Life Viewer Source Code
  9. * The source code in this file ("Source Code") is provided by Linden Lab
  10. * to you under the terms of the GNU General Public License, version 2.0
  11. * ("GPL"), unless you have obtained a separate licensing agreement
  12. * ("Other License"), formally executed by you and Linden Lab. Terms of
  13. * the GPL can be found in doc/GPL-license.txt in this distribution, or
  14. * online at http://secondlifegrid.net/programs/open_source/licensing/gplv2
  15. *
  16. * There are special exceptions to the terms and conditions of the GPL as
  17. * it is applied to this Source Code. View the full text of the exception
  18. * in the file doc/FLOSS-exception.txt in this software distribution, or
  19. * online at
  20. * http://secondlifegrid.net/programs/open_source/licensing/flossexception
  21. *
  22. * By copying, modifying or distributing this software, you acknowledge
  23. * that you have read and understood your obligations described above,
  24. * and agree to abide by those obligations.
  25. *
  26. * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
  27. * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
  28. * COMPLETENESS OR PERFORMANCE.
  29. * $/LicenseInfo$
  30. */
  31. #ifndef LLSINGLETON_H
  32. #define LLSINGLETON_H
  33. #include <typeinfo>
  34. #include "hbfastmap.h"
  35. #include "llstring.h" // For hash_value(const std::string&) override
  36. // A global registry of all singletons to prevent duplicate allocations across
  37. // shared library boundaries
  38. class LLSingletonRegistry
  39. {
  40. private:
  41. typedef safe_hmap<std::string, void*> type_map_t;
  42. static type_map_t* sSingletonMap;
  43. static void checkInit()
  44. {
  45. if (!sSingletonMap)
  46. {
  47. sSingletonMap = new type_map_t();
  48. }
  49. }
  50. public:
  51. template<typename T> static void*& get()
  52. {
  53. std::string name(typeid(T).name());
  54. checkInit();
  55. // The first entry of the pair returned by insert will be either the
  56. // existing iterator matching our key, or the newly inserted NULL
  57. // initialized entry see "Insert element" in:
  58. // http://www.sgi.com/tech/stl/UniqueAssociativeContainer.html
  59. type_map_t::iterator it = sSingletonMap->emplace(name, nullptr).first;
  60. return it->second;
  61. }
  62. };
  63. // LLSingleton implements the getInstance() method part of the Singleton
  64. // pattern. It cannot make the derived class constructors protected, though, so
  65. // you have to do that yourself.
  66. //
  67. // Derive your class from LLSingleton, passing your subclass name as
  68. // LLSingleton's template parameter, like so:
  69. //
  70. // class Foo : public LLSingleton<Foo>
  71. // {
  72. // friend class LLSingleton<Foo>;
  73. //
  74. // protected:
  75. // LOG_CLASS(Foo);
  76. //
  77. // .../...
  78. // };
  79. //
  80. // Foo* instance = Foo::getInstance();
  81. //
  82. // As currently written, LLSingleton is not thread-safe.
  83. // This is to avoid inlining llerrs and llwarns...
  84. LL_NO_INLINE void errorUsedInConstructor(const std::type_info& type);
  85. LL_NO_INLINE void warnAccessingDeletedSingleton(const std::type_info& type);
  86. template <typename DERIVED_TYPE>
  87. class LLSingleton
  88. {
  89. private:
  90. typedef enum e_init_state
  91. {
  92. UNINITIALIZED,
  93. CONSTRUCTING,
  94. INITIALIZING,
  95. INITIALIZED,
  96. DELETED
  97. } EInitState;
  98. // Stores pointer to singleton instance and tracks initialization state of
  99. // the singleton.
  100. struct SingletonInstanceData
  101. {
  102. EInitState mInitState;
  103. DERIVED_TYPE* mSingletonInstance;
  104. SingletonInstanceData()
  105. : mSingletonInstance(NULL),
  106. mInitState(UNINITIALIZED)
  107. {
  108. }
  109. ~SingletonInstanceData()
  110. {
  111. if (mInitState != DELETED)
  112. {
  113. deleteSingleton();
  114. }
  115. }
  116. };
  117. public:
  118. virtual ~LLSingleton()
  119. {
  120. SingletonInstanceData& data = getData();
  121. data.mSingletonInstance = NULL;
  122. data.mInitState = DELETED;
  123. }
  124. // Non-copyable
  125. LLSingleton& operator=(const LLSingleton&) = delete;
  126. // This method merely exists to minimize the amount of inlined code, since
  127. // it normally only gets called once for each singleton and is therefore
  128. // not time-critical
  129. static void createSingleton()
  130. {
  131. SingletonInstanceData& data = getData();
  132. data.mInitState = CONSTRUCTING;
  133. data.mSingletonInstance = new DERIVED_TYPE();
  134. data.mInitState = INITIALIZING;
  135. data.mSingletonInstance->initSingleton();
  136. data.mInitState = INITIALIZED;
  137. }
  138. /**
  139. * @brief Immediately delete the singleton.
  140. *
  141. * A subsequent call to LLProxy::getInstance() will construct a new
  142. * instance of the class.
  143. *
  144. * LLSingletons are normally destroyed after main() has exited and the C++
  145. * runtime is cleaning up statically-constructed objects. Some classes
  146. * derived from LLSingleton have objects that are part of a runtime system
  147. * that is terminated before main() exits. Calling the destructor of those
  148. * objects after the termination of their respective systems can cause
  149. * crashes and other problems during termination of the project. Using this
  150. * method to destroy the singleton early can prevent these crashes.
  151. *
  152. * An example where this is needed is for a LLSingleton that has an APR
  153. * object as a member that makes APR calls on destruction. The APR system
  154. * is shut down explicitly before main() exits. This causes a crash on
  155. * exit. Using this method before the call to apr_terminate() and NOT
  156. * calling getInstance() again will prevent the crash.
  157. */
  158. static void deleteSingleton()
  159. {
  160. delete getData().mSingletonInstance;
  161. getData().mSingletonInstance = NULL;
  162. getData().mInitState = DELETED;
  163. }
  164. static LL_INLINE SingletonInstanceData& getData()
  165. {
  166. // This is static to cache the lookup results
  167. static void*& registry = LLSingletonRegistry::get<DERIVED_TYPE>();
  168. // *TODO - look into making this threadsafe
  169. if (!registry)
  170. {
  171. static SingletonInstanceData data;
  172. registry = &data;
  173. }
  174. return *static_cast<SingletonInstanceData*>(registry);
  175. }
  176. static LL_INLINE DERIVED_TYPE* getInstance()
  177. {
  178. SingletonInstanceData& data = getData();
  179. if (data.mInitState == CONSTRUCTING)
  180. {
  181. errorUsedInConstructor(typeid(DERIVED_TYPE));
  182. }
  183. else if (data.mInitState == DELETED)
  184. {
  185. warnAccessingDeletedSingleton(typeid(DERIVED_TYPE));
  186. }
  187. if (!data.mSingletonInstance)
  188. {
  189. createSingleton();
  190. }
  191. return data.mSingletonInstance;
  192. }
  193. // Has this singleton been created yet ? Use this to avoid accessing
  194. // singletons before they can safely be constructed.
  195. static LL_INLINE bool instanceExists()
  196. {
  197. return getData().mInitState == INITIALIZED;
  198. }
  199. // Has this singleton already been deleted ?
  200. // Use this to avoid accessing singletons from a static object destructor.
  201. static LL_INLINE bool destroyed()
  202. {
  203. return getData().mInitState == DELETED;
  204. }
  205. private:
  206. virtual void initSingleton() {}
  207. };
  208. #endif // LLSINGLETON_H