You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

spinlock.h 12 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. //
  2. // Copyright 2017 The Abseil Authors.
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. //
  8. // https://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. //
  16. // Most users requiring mutual exclusion should use Mutex.
  17. // SpinLock is provided for use in two situations:
  18. // - for use by Abseil internal code that Mutex itself depends on
  19. // - for async signal safety (see below)
  20. // SpinLock is async signal safe. If a spinlock is used within a signal
  21. // handler, all code that acquires the lock must ensure that the signal cannot
  22. // arrive while they are holding the lock. Typically, this is done by blocking
  23. // the signal.
  24. //
  25. // Threads waiting on a SpinLock may be woken in an arbitrary order.
  26. #ifndef ABSL_BASE_INTERNAL_SPINLOCK_H_
  27. #define ABSL_BASE_INTERNAL_SPINLOCK_H_
  28. #include <stdint.h>
  29. #include <sys/types.h>
  30. #include <atomic>
  31. #include "absl/base/attributes.h"
  32. #include "absl/base/const_init.h"
  33. #include "absl/base/dynamic_annotations.h"
  34. #include "absl/base/internal/low_level_scheduling.h"
  35. #include "absl/base/internal/raw_logging.h"
  36. #include "absl/base/internal/scheduling_mode.h"
  37. #include "absl/base/internal/tsan_mutex_interface.h"
  38. #include "absl/base/macros.h"
  39. #include "absl/base/port.h"
  40. #include "absl/base/thread_annotations.h"
  41. namespace absl
  42. {
  43. ABSL_NAMESPACE_BEGIN
  44. namespace base_internal
  45. {
  46. class ABSL_LOCKABLE SpinLock
  47. {
  48. public:
  49. SpinLock() :
  50. lockword_(kSpinLockCooperative)
  51. {
  52. ABSL_TSAN_MUTEX_CREATE(this, __tsan_mutex_not_static);
  53. }
  54. // Constructors that allow non-cooperative spinlocks to be created for use
  55. // inside thread schedulers. Normal clients should not use these.
  56. explicit SpinLock(base_internal::SchedulingMode mode);
  57. // Constructor for global SpinLock instances. See absl/base/const_init.h.
  58. constexpr SpinLock(absl::ConstInitType, base_internal::SchedulingMode mode) :
  59. lockword_(IsCooperative(mode) ? kSpinLockCooperative : 0)
  60. {
  61. }
  62. // For global SpinLock instances prefer trivial destructor when possible.
  63. // Default but non-trivial destructor in some build configurations causes an
  64. // extra static initializer.
  65. #ifdef ABSL_INTERNAL_HAVE_TSAN_INTERFACE
  66. ~SpinLock()
  67. {
  68. ABSL_TSAN_MUTEX_DESTROY(this, __tsan_mutex_not_static);
  69. }
  70. #else
  71. ~SpinLock() = default;
  72. #endif
  73. // Acquire this SpinLock.
  74. inline void Lock() ABSL_EXCLUSIVE_LOCK_FUNCTION()
  75. {
  76. ABSL_TSAN_MUTEX_PRE_LOCK(this, 0);
  77. if (!TryLockImpl())
  78. {
  79. SlowLock();
  80. }
  81. ABSL_TSAN_MUTEX_POST_LOCK(this, 0, 0);
  82. }
  83. // Try to acquire this SpinLock without blocking and return true if the
  84. // acquisition was successful. If the lock was not acquired, false is
  85. // returned. If this SpinLock is free at the time of the call, TryLock
  86. // will return true with high probability.
  87. inline bool TryLock() ABSL_EXCLUSIVE_TRYLOCK_FUNCTION(true)
  88. {
  89. ABSL_TSAN_MUTEX_PRE_LOCK(this, __tsan_mutex_try_lock);
  90. bool res = TryLockImpl();
  91. ABSL_TSAN_MUTEX_POST_LOCK(
  92. this, __tsan_mutex_try_lock | (res ? 0 : __tsan_mutex_try_lock_failed), 0
  93. );
  94. return res;
  95. }
  96. // Release this SpinLock, which must be held by the calling thread.
  97. inline void Unlock() ABSL_UNLOCK_FUNCTION()
  98. {
  99. ABSL_TSAN_MUTEX_PRE_UNLOCK(this, 0);
  100. uint32_t lock_value = lockword_.load(std::memory_order_relaxed);
  101. lock_value = lockword_.exchange(lock_value & kSpinLockCooperative, std::memory_order_release);
  102. if ((lock_value & kSpinLockDisabledScheduling) != 0)
  103. {
  104. base_internal::SchedulingGuard::EnableRescheduling(true);
  105. }
  106. if ((lock_value & kWaitTimeMask) != 0)
  107. {
  108. // Collect contentionz profile info, and speed the wakeup of any waiter.
  109. // The wait_cycles value indicates how long this thread spent waiting
  110. // for the lock.
  111. SlowUnlock(lock_value);
  112. }
  113. ABSL_TSAN_MUTEX_POST_UNLOCK(this, 0);
  114. }
  115. // Determine if the lock is held. When the lock is held by the invoking
  116. // thread, true will always be returned. Intended to be used as
  117. // CHECK(lock.IsHeld()).
  118. inline bool IsHeld() const
  119. {
  120. return (lockword_.load(std::memory_order_relaxed) & kSpinLockHeld) != 0;
  121. }
  122. // Return immediately if this thread holds the SpinLock exclusively.
  123. // Otherwise, report an error by crashing with a diagnostic.
  124. inline void AssertHeld() const ABSL_ASSERT_EXCLUSIVE_LOCK()
  125. {
  126. if (!IsHeld())
  127. {
  128. ABSL_RAW_LOG(FATAL, "thread should hold the lock on SpinLock");
  129. }
  130. }
  131. protected:
  132. // These should not be exported except for testing.
  133. // Store number of cycles between wait_start_time and wait_end_time in a
  134. // lock value.
  135. static uint32_t EncodeWaitCycles(int64_t wait_start_time, int64_t wait_end_time);
  136. // Extract number of wait cycles in a lock value.
  137. static uint64_t DecodeWaitCycles(uint32_t lock_value);
  138. // Provide access to protected method above. Use for testing only.
  139. friend struct SpinLockTest;
  140. private:
  141. // lockword_ is used to store the following:
  142. //
  143. // bit[0] encodes whether a lock is being held.
  144. // bit[1] encodes whether a lock uses cooperative scheduling.
  145. // bit[2] encodes whether the current lock holder disabled scheduling when
  146. // acquiring the lock. Only set when kSpinLockHeld is also set.
  147. // bit[3:31] encodes time a lock spent on waiting as a 29-bit unsigned int.
  148. // This is set by the lock holder to indicate how long it waited on
  149. // the lock before eventually acquiring it. The number of cycles is
  150. // encoded as a 29-bit unsigned int, or in the case that the current
  151. // holder did not wait but another waiter is queued, the LSB
  152. // (kSpinLockSleeper) is set. The implementation does not explicitly
  153. // track the number of queued waiters beyond this. It must always be
  154. // assumed that waiters may exist if the current holder was required to
  155. // queue.
  156. //
  157. // Invariant: if the lock is not held, the value is either 0 or
  158. // kSpinLockCooperative.
  159. static constexpr uint32_t kSpinLockHeld = 1;
  160. static constexpr uint32_t kSpinLockCooperative = 2;
  161. static constexpr uint32_t kSpinLockDisabledScheduling = 4;
  162. static constexpr uint32_t kSpinLockSleeper = 8;
  163. // Includes kSpinLockSleeper.
  164. static constexpr uint32_t kWaitTimeMask =
  165. ~(kSpinLockHeld | kSpinLockCooperative | kSpinLockDisabledScheduling);
  166. // Returns true if the provided scheduling mode is cooperative.
  167. static constexpr bool IsCooperative(
  168. base_internal::SchedulingMode scheduling_mode
  169. )
  170. {
  171. return scheduling_mode == base_internal::SCHEDULE_COOPERATIVE_AND_KERNEL;
  172. }
  173. uint32_t TryLockInternal(uint32_t lock_value, uint32_t wait_cycles);
  174. void SlowLock() ABSL_ATTRIBUTE_COLD;
  175. void SlowUnlock(uint32_t lock_value) ABSL_ATTRIBUTE_COLD;
  176. uint32_t SpinLoop();
  177. inline bool TryLockImpl()
  178. {
  179. uint32_t lock_value = lockword_.load(std::memory_order_relaxed);
  180. return (TryLockInternal(lock_value, 0) & kSpinLockHeld) == 0;
  181. }
  182. std::atomic<uint32_t> lockword_;
  183. SpinLock(const SpinLock&) = delete;
  184. SpinLock& operator=(const SpinLock&) = delete;
  185. };
  186. // Corresponding locker object that arranges to acquire a spinlock for
  187. // the duration of a C++ scope.
  188. class ABSL_SCOPED_LOCKABLE SpinLockHolder
  189. {
  190. public:
  191. inline explicit SpinLockHolder(SpinLock* l) ABSL_EXCLUSIVE_LOCK_FUNCTION(l) :
  192. lock_(l)
  193. {
  194. l->Lock();
  195. }
  196. inline ~SpinLockHolder() ABSL_UNLOCK_FUNCTION()
  197. {
  198. lock_->Unlock();
  199. }
  200. SpinLockHolder(const SpinLockHolder&) = delete;
  201. SpinLockHolder& operator=(const SpinLockHolder&) = delete;
  202. private:
  203. SpinLock* lock_;
  204. };
  205. // Register a hook for profiling support.
  206. //
  207. // The function pointer registered here will be called whenever a spinlock is
  208. // contended. The callback is given an opaque handle to the contended spinlock
  209. // and the number of wait cycles. This is thread-safe, but only a single
  210. // profiler can be registered. It is an error to call this function multiple
  211. // times with different arguments.
  212. void RegisterSpinLockProfiler(void (*fn)(const void* lock, int64_t wait_cycles));
  213. //------------------------------------------------------------------------------
  214. // Public interface ends here.
  215. //------------------------------------------------------------------------------
  216. // If (result & kSpinLockHeld) == 0, then *this was successfully locked.
  217. // Otherwise, returns last observed value for lockword_.
  218. inline uint32_t SpinLock::TryLockInternal(uint32_t lock_value, uint32_t wait_cycles)
  219. {
  220. if ((lock_value & kSpinLockHeld) != 0)
  221. {
  222. return lock_value;
  223. }
  224. uint32_t sched_disabled_bit = 0;
  225. if ((lock_value & kSpinLockCooperative) == 0)
  226. {
  227. // For non-cooperative locks we must make sure we mark ourselves as
  228. // non-reschedulable before we attempt to CompareAndSwap.
  229. if (base_internal::SchedulingGuard::DisableRescheduling())
  230. {
  231. sched_disabled_bit = kSpinLockDisabledScheduling;
  232. }
  233. }
  234. if (!lockword_.compare_exchange_strong(
  235. lock_value,
  236. kSpinLockHeld | lock_value | wait_cycles | sched_disabled_bit,
  237. std::memory_order_acquire,
  238. std::memory_order_relaxed
  239. ))
  240. {
  241. base_internal::SchedulingGuard::EnableRescheduling(sched_disabled_bit != 0);
  242. }
  243. return lock_value;
  244. }
  245. } // namespace base_internal
  246. ABSL_NAMESPACE_END
  247. } // namespace absl
  248. #endif // ABSL_BASE_INTERNAL_SPINLOCK_H_