thread_local_storage.h 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. // Copyright (c) 2012 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. #ifndef BASE_THREADING_THREAD_LOCAL_STORAGE_H_
  5. #define BASE_THREADING_THREAD_LOCAL_STORAGE_H_
  6. #include <stdint.h>
  7. #include "base/atomicops.h"
  8. #include "base/base_export.h"
  9. #include "base/macros.h"
  10. #include "build/build_config.h"
  11. #if defined(OS_WIN)
  12. #include "base/win/windows_types.h"
  13. #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
  14. #include <pthread.h>
  15. #endif
  16. namespace ui {
  17. class TLSDestructionCheckerForX11;
  18. }
  19. namespace base {
  20. class SamplingHeapProfiler;
  21. namespace debug {
  22. class GlobalActivityTracker;
  23. } // namespace debug
  24. namespace trace_event {
  25. class MallocDumpProvider;
  26. } // namespace trace_event
  27. namespace internal {
  28. class ThreadLocalStorageTestInternal;
  29. // WARNING: You should *NOT* use this class directly.
  30. // PlatformThreadLocalStorage is a low-level abstraction of the OS's TLS
  31. // interface. Instead, you should use one of the following:
  32. // * ThreadLocalBoolean (from thread_local.h) for booleans.
  33. // * ThreadLocalPointer (from thread_local.h) for pointers.
  34. // * ThreadLocalStorage::StaticSlot/Slot for more direct control of the slot.
  35. class BASE_EXPORT PlatformThreadLocalStorage {
  36. public:
  37. #if defined(OS_WIN)
  38. typedef unsigned long TLSKey;
  39. enum : unsigned { TLS_KEY_OUT_OF_INDEXES = TLS_OUT_OF_INDEXES };
  40. #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
  41. typedef pthread_key_t TLSKey;
  42. // The following is a "reserved key" which is used in our generic Chromium
  43. // ThreadLocalStorage implementation. We expect that an OS will not return
  44. // such a key, but if it is returned (i.e., the OS tries to allocate it) we
  45. // will just request another key.
  46. enum { TLS_KEY_OUT_OF_INDEXES = 0x7FFFFFFF };
  47. #endif
  48. // The following methods need to be supported on each OS platform, so that
  49. // the Chromium ThreadLocalStore functionality can be constructed.
  50. // Chromium will use these methods to acquire a single OS slot, and then use
  51. // that to support a much larger number of Chromium slots (independent of the
  52. // OS restrictions).
  53. // The following returns true if it successfully is able to return an OS
  54. // key in |key|.
  55. static bool AllocTLS(TLSKey* key);
  56. // Note: FreeTLS() doesn't have to be called, it is fine with this leak, OS
  57. // might not reuse released slot, you might just reset the TLS value with
  58. // SetTLSValue().
  59. static void FreeTLS(TLSKey key);
  60. static void SetTLSValue(TLSKey key, void* value);
  61. static void* GetTLSValue(TLSKey key) {
  62. #if defined(OS_WIN)
  63. return TlsGetValue(key);
  64. #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
  65. return pthread_getspecific(key);
  66. #endif
  67. }
  68. // Each platform (OS implementation) is required to call this method on each
  69. // terminating thread when the thread is about to terminate. This method
  70. // will then call all registered destructors for slots in Chromium
  71. // ThreadLocalStorage, until there are no slot values remaining as having
  72. // been set on this thread.
  73. // Destructors may end up being called multiple times on a terminating
  74. // thread, as other destructors may re-set slots that were previously
  75. // destroyed.
  76. #if defined(OS_WIN)
  77. // Since Windows which doesn't support TLS destructor, the implementation
  78. // should use GetTLSValue() to retrieve the value of TLS slot.
  79. static void OnThreadExit();
  80. #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
  81. // |Value| is the data stored in TLS slot, The implementation can't use
  82. // GetTLSValue() to retrieve the value of slot as it has already been reset
  83. // in Posix.
  84. static void OnThreadExit(void* value);
  85. #endif
  86. };
  87. } // namespace internal
  88. // Wrapper for thread local storage. This class doesn't do much except provide
  89. // an API for portability.
  90. class BASE_EXPORT ThreadLocalStorage {
  91. public:
  92. // Prototype for the TLS destructor function, which can be optionally used to
  93. // cleanup thread local storage on thread exit. 'value' is the data that is
  94. // stored in thread local storage.
  95. typedef void (*TLSDestructorFunc)(void* value);
  96. // A key representing one value stored in TLS. Use as a class member or a
  97. // local variable. If you need a static storage duration variable, use the
  98. // following pattern with a NoDestructor<Slot>:
  99. // void MyDestructorFunc(void* value);
  100. // ThreadLocalStorage::Slot& ImportantContentTLS() {
  101. // static NoDestructor<ThreadLocalStorage::Slot> important_content_tls(
  102. // &MyDestructorFunc);
  103. // return *important_content_tls;
  104. // }
  105. class BASE_EXPORT Slot final {
  106. public:
  107. // |destructor| is a pointer to a function to perform per-thread cleanup of
  108. // this object. If set to nullptr, no cleanup is done for this TLS slot.
  109. explicit Slot(TLSDestructorFunc destructor = nullptr);
  110. // If a destructor was set for this slot, removes the destructor so that
  111. // remaining threads exiting will not free data.
  112. ~Slot();
  113. // Get the thread-local value stored in slot 'slot'.
  114. // Values are guaranteed to initially be zero.
  115. void* Get() const;
  116. // Set the thread-local value stored in slot 'slot' to
  117. // value 'value'.
  118. void Set(void* value);
  119. private:
  120. void Initialize(TLSDestructorFunc destructor);
  121. void Free();
  122. static constexpr int kInvalidSlotValue = -1;
  123. int slot_ = kInvalidSlotValue;
  124. uint32_t version_ = 0;
  125. DISALLOW_COPY_AND_ASSIGN(Slot);
  126. };
  127. private:
  128. // In most cases, most callers should not need access to HasBeenDestroyed().
  129. // If you are working in code that runs during thread destruction, contact the
  130. // base OWNERs for advice and then make a friend request.
  131. //
  132. // Returns |true| if Chrome's implementation of TLS is being or has been
  133. // destroyed during thread destruction. Attempting to call Slot::Get() during
  134. // destruction is disallowed and will hit a DCHECK. Any code that relies on
  135. // TLS during thread destruction must first check this method before calling
  136. // Slot::Get().
  137. friend class SequenceCheckerImpl;
  138. friend class SamplingHeapProfiler;
  139. friend class ThreadCheckerImpl;
  140. friend class internal::ThreadLocalStorageTestInternal;
  141. friend class trace_event::MallocDumpProvider;
  142. friend class debug::GlobalActivityTracker;
  143. friend class ui::TLSDestructionCheckerForX11;
  144. static bool HasBeenDestroyed();
  145. DISALLOW_COPY_AND_ASSIGN(ThreadLocalStorage);
  146. };
  147. } // namespace base
  148. #endif // BASE_THREADING_THREAD_LOCAL_STORAGE_H_