tls.h 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. #pragma once
  2. #include "defaults.h"
  3. #include <util/generic/ptr.h>
  4. #include <util/generic/noncopyable.h>
  5. #include <new>
  6. #if defined(_darwin_)
  7. #define Y_DISABLE_THRKEY_OPTIMIZATION
  8. #endif
  9. #if defined(_arm_) && defined(_linux_)
  10. #define Y_DISABLE_THRKEY_OPTIMIZATION
  11. #endif
  12. #if defined(__GNUC__) && defined(__ANDROID__) && defined(__i686__) // https://st.yandex-team.ru/DEVTOOLS-3352
  13. #define Y_DISABLE_THRKEY_OPTIMIZATION
  14. #endif
  15. /**
  16. @def Y_THREAD(TType)
  17. A thread-local wrapper for a given class. Suitable for POD and classes with a constructor with a single argument.
  18. The wrapper can be treated as the original class in many cases, as it has the same signature for the constructor and an implicit cast to the origianl class.
  19. Has methods :
  20. - implicit caster to TType
  21. - TType& Get()
  22. - TType* GetPtr()
  23. Time complexity: getting a variable takes O(number of threads where the variable has been constructed)
  24. Memory usage: O(number of threads where the variable has been constructed)
  25. Best practices:
  26. - storing singletons won't result in heavy memory overheads
  27. - storing pointers allows complex constructors as well as lazy constructions
  28. - storing static variables won't result in heavy memory overheads
  29. Possibly bad practices:
  30. - field in a class with numerous instances and numerous threads will result in slow working and memory overheads
  31. Example:
  32. @code
  33. // the field declaration in header
  34. Y_THREAD(TBuffer) TmpBuffer;
  35. // ...later somewhere in cpp...
  36. TmpBuffer.Clear();
  37. for (size_t i = 0; i < sz && TrieCursor[i].second.IsFork(); ++i) {
  38. TmpBuffer.Append(TrieCursor[i].second.Char);
  39. }
  40. @endcode
  41. Example:
  42. @code
  43. // the field decalrataion in header
  44. Y_THREAD(TMyWriter*) ThreadLocalWriter;
  45. // ...later somewhere in cpp...
  46. TMyWriter*& writerRef = ThreadLocalWriter.Get();
  47. if (writerRef == nullptr) {
  48. THolder<TMyWriter> threadLocalWriter( new TMyWriter(
  49. *Session,
  50. MinLogError,
  51. MaxRps,
  52. LogFraction,
  53. WriteCounters,
  54. Log));
  55. writerRef = threadLocalWriter.Get();
  56. }
  57. @endcode
  58. Example:
  59. @code
  60. // in header
  61. namespace TMorph {
  62. Y_THREAD(ELanguage) ThreadLocalMainLanguage;
  63. }
  64. // in cpp
  65. Y_THREAD(ELanguage) TMorph::ThreadLocalMainLanguage(LANG_RUS);
  66. @endcode
  67. Example:
  68. @code
  69. Y_THREAD(TScoreCalcer*) ScoreCalcerPtr;
  70. static TScoreCalcer* GetScoreCalcer(yint maxElemCount) {
  71. if (ScoreCalcerPtr == 0) {
  72. ScoreCalcerPtr = new TScoreCalcer();
  73. ScoreCalcerPtr->Alloc(maxElemCount);
  74. }
  75. return ScoreCalcerPtr;
  76. }
  77. @endcode
  78. @param TType POD or a class with a constructor taking 1 argument
  79. **/
  80. /**
  81. @def Y_STATIC_THREAD(TType)
  82. Equivalent to "static Y_THREAD(TType)"
  83. @see Y_THREAD(TType)
  84. **/
  85. /**
  86. @def Y_POD_THREAD(TType)
  87. Same interface as Y_THREAD(TType), but TType must be a POD.
  88. Implemented (based on the compiler) as Y_THREAD(TType) or as native tls.
  89. @see Y_THREAD(TType)
  90. **/
  91. /**
  92. @def STATIC_POD_THREAD(TType)
  93. Equivalent to "static Y_POD_THREAD(TType)"
  94. @see Y_POD_THREAD(TType)
  95. **/
  96. #define Y_THREAD(T) ::NTls::TValue<T>
  97. #define Y_STATIC_THREAD(T) static Y_THREAD(T)
  98. // gcc and msvc support automatic tls for POD types
  99. #if defined(Y_DISABLE_THRKEY_OPTIMIZATION)
  100. // nothing to do
  101. #elif defined(__clang__)
  102. #define Y_POD_THREAD(T) thread_local T
  103. #define Y_POD_STATIC_THREAD(T) static thread_local T
  104. #elif defined(__GNUC__) && !defined(_cygwin_) && !defined(_arm_) && !defined(__IOS_SIMULATOR__)
  105. #define Y_POD_THREAD(T) __thread T
  106. #define Y_POD_STATIC_THREAD(T) static __thread T
  107. // msvc doesn't support __declspec(thread) in dlls, loaded manually (via LoadLibrary)
  108. #elif (defined(_MSC_VER) && !defined(_WINDLL)) || defined(_arm_)
  109. #define Y_POD_THREAD(T) __declspec(thread) T
  110. #define Y_POD_STATIC_THREAD(T) __declspec(thread) static T
  111. #endif
  112. #if !defined(Y_POD_THREAD) || !defined(Y_POD_STATIC_THREAD)
  113. #define Y_POD_THREAD(T) Y_THREAD(T)
  114. #define Y_POD_STATIC_THREAD(T) Y_STATIC_THREAD(T)
  115. #else
  116. #define Y_HAVE_FAST_POD_TLS
  117. #endif
  118. namespace NPrivate {
  119. void FillWithTrash(void* ptr, size_t len);
  120. } // namespace NPrivate
  121. namespace NTls {
  122. using TDtor = void (*)(void*);
  123. class TKey {
  124. public:
  125. TKey(TDtor dtor);
  126. TKey(TKey&&) noexcept;
  127. ~TKey();
  128. void* Get() const;
  129. void Set(void* ptr) const;
  130. static void Cleanup() noexcept;
  131. private:
  132. class TImpl;
  133. THolder<TImpl> Impl_;
  134. };
  135. struct TCleaner {
  136. inline ~TCleaner() {
  137. TKey::Cleanup();
  138. }
  139. };
  140. template <class T>
  141. class TValue: public TMoveOnly {
  142. class TConstructor {
  143. public:
  144. TConstructor() noexcept = default;
  145. virtual ~TConstructor() = default;
  146. virtual T* Construct(void* ptr) const = 0;
  147. };
  148. class TDefaultConstructor: public TConstructor {
  149. public:
  150. ~TDefaultConstructor() override = default;
  151. T* Construct(void* ptr) const override {
  152. // memset(ptr, 0, sizeof(T));
  153. return ::new (ptr) T();
  154. }
  155. };
  156. template <class T1>
  157. class TCopyConstructor: public TConstructor {
  158. public:
  159. inline TCopyConstructor(const T1& value)
  160. : Value(value)
  161. {
  162. }
  163. ~TCopyConstructor() override = default;
  164. T* Construct(void* ptr) const override {
  165. return ::new (ptr) T(Value);
  166. }
  167. private:
  168. T1 Value;
  169. };
  170. public:
  171. inline TValue()
  172. : Constructor_(new TDefaultConstructor())
  173. , Key_(Dtor)
  174. {
  175. }
  176. template <class T1>
  177. inline TValue(const T1& value)
  178. : Constructor_(new TCopyConstructor<T1>(value))
  179. , Key_(Dtor)
  180. {
  181. }
  182. template <class T1>
  183. inline T& operator=(const T1& val) {
  184. return Get() = val;
  185. }
  186. inline operator const T&() const {
  187. return Get();
  188. }
  189. inline operator T&() {
  190. return Get();
  191. }
  192. inline const T& operator->() const {
  193. return Get();
  194. }
  195. inline T& operator->() {
  196. return Get();
  197. }
  198. inline const T* operator&() const {
  199. return GetPtr();
  200. }
  201. inline T* operator&() {
  202. return GetPtr();
  203. }
  204. inline T& Get() const {
  205. return *GetPtr();
  206. }
  207. inline T* GetPtr() const {
  208. T* val = static_cast<T*>(Key_.Get());
  209. if (!val) {
  210. THolder<void> mem(::operator new(sizeof(T)));
  211. THolder<T> newval(Constructor_->Construct(mem.Get()));
  212. Y_UNUSED(mem.Release());
  213. Key_.Set((void*)newval.Get());
  214. val = newval.Release();
  215. }
  216. return val;
  217. }
  218. private:
  219. static void Dtor(void* ptr) {
  220. THolder<void> mem(ptr);
  221. ((T*)ptr)->~T();
  222. ::NPrivate::FillWithTrash(ptr, sizeof(T));
  223. }
  224. private:
  225. THolder<TConstructor> Constructor_;
  226. TKey Key_;
  227. };
  228. } // namespace NTls
  229. template <class T>
  230. static inline T& TlsRef(NTls::TValue<T>& v) noexcept {
  231. return v;
  232. }
  233. template <class T>
  234. static inline const T& TlsRef(const NTls::TValue<T>& v) noexcept {
  235. return v;
  236. }
  237. template <class T>
  238. static inline T& TlsRef(T& v) noexcept {
  239. return v;
  240. }