spinlock.h
Go to the documentation of this file.
00001 //
00002 // Copyright 2017 The Abseil Authors.
00003 //
00004 // Licensed under the Apache License, Version 2.0 (the "License");
00005 // you may not use this file except in compliance with the License.
00006 // You may obtain a copy of the License at
00007 //
00008 //      https://www.apache.org/licenses/LICENSE-2.0
00009 //
00010 // Unless required by applicable law or agreed to in writing, software
00011 // distributed under the License is distributed on an "AS IS" BASIS,
00012 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
00013 // See the License for the specific language governing permissions and
00014 // limitations under the License.
00015 //
00016 
00017 //  Most users requiring mutual exclusion should use Mutex.
00018 //  SpinLock is provided for use in three situations:
00019 //   - for use in code that Mutex itself depends on
00020 //   - to get a faster fast-path release under low contention (without an
00021 //     atomic read-modify-write) In return, SpinLock has worse behaviour under
00022 //     contention, which is why Mutex is preferred in most situations.
00023 //   - for async signal safety (see below)
00024 
00025 // SpinLock is async signal safe.  If a spinlock is used within a signal
00026 // handler, all code that acquires the lock must ensure that the signal cannot
00027 // arrive while they are holding the lock.  Typically, this is done by blocking
00028 // the signal.
00029 
00030 #ifndef ABSL_BASE_INTERNAL_SPINLOCK_H_
00031 #define ABSL_BASE_INTERNAL_SPINLOCK_H_
00032 
00033 #include <stdint.h>
00034 #include <sys/types.h>
00035 
00036 #include <atomic>
00037 
00038 #include "absl/base/attributes.h"
00039 #include "absl/base/dynamic_annotations.h"
00040 #include "absl/base/internal/low_level_scheduling.h"
00041 #include "absl/base/internal/raw_logging.h"
00042 #include "absl/base/internal/scheduling_mode.h"
00043 #include "absl/base/internal/tsan_mutex_interface.h"
00044 #include "absl/base/macros.h"
00045 #include "absl/base/port.h"
00046 #include "absl/base/thread_annotations.h"
00047 
00048 namespace absl {
00049 namespace base_internal {
00050 
00051 class LOCKABLE SpinLock {
00052  public:
00053   SpinLock() : lockword_(kSpinLockCooperative) {
00054     ABSL_TSAN_MUTEX_CREATE(this, __tsan_mutex_not_static);
00055   }
00056 
00057   // Special constructor for use with static SpinLock objects.  E.g.,
00058   //
00059   //    static SpinLock lock(base_internal::kLinkerInitialized);
00060   //
00061   // When initialized using this constructor, we depend on the fact
00062   // that the linker has already initialized the memory appropriately. The lock
00063   // is initialized in non-cooperative mode.
00064   //
00065   // A SpinLock constructed like this can be freely used from global
00066   // initializers without worrying about the order in which global
00067   // initializers run.
00068   explicit SpinLock(base_internal::LinkerInitialized) {
00069     // Does nothing; lockword_ is already initialized
00070     ABSL_TSAN_MUTEX_CREATE(this, 0);
00071   }
00072 
00073   // Constructors that allow non-cooperative spinlocks to be created for use
00074   // inside thread schedulers.  Normal clients should not use these.
00075   explicit SpinLock(base_internal::SchedulingMode mode);
00076   SpinLock(base_internal::LinkerInitialized,
00077            base_internal::SchedulingMode mode);
00078 
00079   ~SpinLock() { ABSL_TSAN_MUTEX_DESTROY(this, __tsan_mutex_not_static); }
00080 
00081   // Acquire this SpinLock.
00082   inline void Lock() EXCLUSIVE_LOCK_FUNCTION() {
00083     ABSL_TSAN_MUTEX_PRE_LOCK(this, 0);
00084     if (!TryLockImpl()) {
00085       SlowLock();
00086     }
00087     ABSL_TSAN_MUTEX_POST_LOCK(this, 0, 0);
00088   }
00089 
00090   // Try to acquire this SpinLock without blocking and return true if the
00091   // acquisition was successful.  If the lock was not acquired, false is
00092   // returned.  If this SpinLock is free at the time of the call, TryLock
00093   // will return true with high probability.
00094   inline bool TryLock() EXCLUSIVE_TRYLOCK_FUNCTION(true) {
00095     ABSL_TSAN_MUTEX_PRE_LOCK(this, __tsan_mutex_try_lock);
00096     bool res = TryLockImpl();
00097     ABSL_TSAN_MUTEX_POST_LOCK(
00098         this, __tsan_mutex_try_lock | (res ? 0 : __tsan_mutex_try_lock_failed),
00099         0);
00100     return res;
00101   }
00102 
00103   // Release this SpinLock, which must be held by the calling thread.
00104   inline void Unlock() UNLOCK_FUNCTION() {
00105     ABSL_TSAN_MUTEX_PRE_UNLOCK(this, 0);
00106     uint32_t lock_value = lockword_.load(std::memory_order_relaxed);
00107     lock_value = lockword_.exchange(lock_value & kSpinLockCooperative,
00108                                     std::memory_order_release);
00109 
00110     if ((lock_value & kSpinLockDisabledScheduling) != 0) {
00111       base_internal::SchedulingGuard::EnableRescheduling(true);
00112     }
00113     if ((lock_value & kWaitTimeMask) != 0) {
00114       // Collect contentionz profile info, and speed the wakeup of any waiter.
00115       // The wait_cycles value indicates how long this thread spent waiting
00116       // for the lock.
00117       SlowUnlock(lock_value);
00118     }
00119     ABSL_TSAN_MUTEX_POST_UNLOCK(this, 0);
00120   }
00121 
00122   // Determine if the lock is held.  When the lock is held by the invoking
00123   // thread, true will always be returned. Intended to be used as
00124   // CHECK(lock.IsHeld()).
00125   inline bool IsHeld() const {
00126     return (lockword_.load(std::memory_order_relaxed) & kSpinLockHeld) != 0;
00127   }
00128 
00129  protected:
00130   // These should not be exported except for testing.
00131 
00132   // Store number of cycles between wait_start_time and wait_end_time in a
00133   // lock value.
00134   static uint32_t EncodeWaitCycles(int64_t wait_start_time,
00135                                    int64_t wait_end_time);
00136 
00137   // Extract number of wait cycles in a lock value.
00138   static uint64_t DecodeWaitCycles(uint32_t lock_value);
00139 
00140   // Provide access to protected method above.  Use for testing only.
00141   friend struct SpinLockTest;
00142 
00143  private:
00144   // lockword_ is used to store the following:
00145   //
00146   // bit[0] encodes whether a lock is being held.
00147   // bit[1] encodes whether a lock uses cooperative scheduling.
00148   // bit[2] encodes whether a lock disables scheduling.
00149   // bit[3:31] encodes time a lock spent on waiting as a 29-bit unsigned int.
00150   enum { kSpinLockHeld = 1 };
00151   enum { kSpinLockCooperative = 2 };
00152   enum { kSpinLockDisabledScheduling = 4 };
00153   enum { kSpinLockSleeper = 8 };
00154   enum { kWaitTimeMask =                      // Includes kSpinLockSleeper.
00155     ~(kSpinLockHeld | kSpinLockCooperative | kSpinLockDisabledScheduling) };
00156 
00157   // Returns true if the provided scheduling mode is cooperative.
00158   static constexpr bool IsCooperative(
00159       base_internal::SchedulingMode scheduling_mode) {
00160     return scheduling_mode == base_internal::SCHEDULE_COOPERATIVE_AND_KERNEL;
00161   }
00162 
00163   uint32_t TryLockInternal(uint32_t lock_value, uint32_t wait_cycles);
00164   void InitLinkerInitializedAndCooperative();
00165   void SlowLock() ABSL_ATTRIBUTE_COLD;
00166   void SlowUnlock(uint32_t lock_value) ABSL_ATTRIBUTE_COLD;
00167   uint32_t SpinLoop();
00168 
00169   inline bool TryLockImpl() {
00170     uint32_t lock_value = lockword_.load(std::memory_order_relaxed);
00171     return (TryLockInternal(lock_value, 0) & kSpinLockHeld) == 0;
00172   }
00173 
00174   std::atomic<uint32_t> lockword_;
00175 
00176   SpinLock(const SpinLock&) = delete;
00177   SpinLock& operator=(const SpinLock&) = delete;
00178 };
00179 
00180 // Corresponding locker object that arranges to acquire a spinlock for
00181 // the duration of a C++ scope.
00182 class SCOPED_LOCKABLE SpinLockHolder {
00183  public:
00184   inline explicit SpinLockHolder(SpinLock* l) EXCLUSIVE_LOCK_FUNCTION(l)
00185       : lock_(l) {
00186     l->Lock();
00187   }
00188   inline ~SpinLockHolder() UNLOCK_FUNCTION() { lock_->Unlock(); }
00189 
00190   SpinLockHolder(const SpinLockHolder&) = delete;
00191   SpinLockHolder& operator=(const SpinLockHolder&) = delete;
00192 
00193  private:
00194   SpinLock* lock_;
00195 };
00196 
00197 // Register a hook for profiling support.
00198 //
00199 // The function pointer registered here will be called whenever a spinlock is
00200 // contended.  The callback is given an opaque handle to the contended spinlock
00201 // and the number of wait cycles.  This is thread-safe, but only a single
00202 // profiler can be registered.  It is an error to call this function multiple
00203 // times with different arguments.
00204 void RegisterSpinLockProfiler(void (*fn)(const void* lock,
00205                                          int64_t wait_cycles));
00206 
00207 //------------------------------------------------------------------------------
00208 // Public interface ends here.
00209 //------------------------------------------------------------------------------
00210 
00211 // If (result & kSpinLockHeld) == 0, then *this was successfully locked.
00212 // Otherwise, returns last observed value for lockword_.
00213 inline uint32_t SpinLock::TryLockInternal(uint32_t lock_value,
00214                                           uint32_t wait_cycles) {
00215   if ((lock_value & kSpinLockHeld) != 0) {
00216     return lock_value;
00217   }
00218 
00219   uint32_t sched_disabled_bit = 0;
00220   if ((lock_value & kSpinLockCooperative) == 0) {
00221     // For non-cooperative locks we must make sure we mark ourselves as
00222     // non-reschedulable before we attempt to CompareAndSwap.
00223     if (base_internal::SchedulingGuard::DisableRescheduling()) {
00224       sched_disabled_bit = kSpinLockDisabledScheduling;
00225     }
00226   }
00227 
00228   if (lockword_.compare_exchange_strong(
00229           lock_value,
00230           kSpinLockHeld | lock_value | wait_cycles | sched_disabled_bit,
00231           std::memory_order_acquire, std::memory_order_relaxed)) {
00232   } else {
00233     base_internal::SchedulingGuard::EnableRescheduling(sched_disabled_bit != 0);
00234   }
00235 
00236   return lock_value;
00237 }
00238 
00239 }  // namespace base_internal
00240 }  // namespace absl
00241 
00242 #endif  // ABSL_BASE_INTERNAL_SPINLOCK_H_


abseil_cpp
Author(s):
autogenerated on Wed Jun 19 2019 19:42:15