spin_lock.h 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. #pragma once
  2. #include "public.h"
  3. #include "spin_lock_base.h"
  4. #include "spin_lock_count.h"
  5. #include <library/cpp/yt/misc/port.h>
  6. #include <library/cpp/yt/system/thread_id.h>
  7. #include <library/cpp/yt/memory/public.h>
  8. #include <util/system/src_location.h>
  9. #include <util/system/types.h>
  10. #include <atomic>
  11. namespace NYT::NThreading {
  12. ////////////////////////////////////////////////////////////////////////////////
  13. //! A slightly modified version of TAdaptiveLock.
  14. /*!
  15. * The lock is unfair.
  16. */
  17. class TSpinLock
  18. : public TSpinLockBase
  19. {
  20. public:
  21. using TSpinLockBase::TSpinLockBase;
  22. //! Acquires the lock.
  23. void Acquire() noexcept;
  24. //! Tries acquiring the lock.
  25. //! Returns |true| on success.
  26. bool TryAcquire() noexcept;
  27. //! Releases the lock.
  28. void Release() noexcept;
  29. //! Returns true if the lock is taken.
  30. /*!
  31. * This is inherently racy.
  32. * Only use for debugging and diagnostic purposes.
  33. */
  34. bool IsLocked() const noexcept;
  35. private:
  36. #ifdef YT_ENABLE_SPIN_LOCK_OWNERSHIP_TRACKING
  37. using TValue = TSequentialThreadId;
  38. static constexpr TValue UnlockedValue = InvalidSequentialThreadId;
  39. #else
  40. using TValue = ui32;
  41. static constexpr TValue UnlockedValue = 0;
  42. static constexpr TValue LockedValue = 1;
  43. #endif
  44. std::atomic<TValue> Value_ = UnlockedValue;
  45. bool TryAndTryAcquire() noexcept;
  46. void AcquireSlow() noexcept;
  47. };
  48. REGISTER_TRACKED_SPIN_LOCK_CLASS(TSpinLock)
  49. ////////////////////////////////////////////////////////////////////////////////
  50. //! A variant of TSpinLock occupying the whole cache line.
  51. class alignas(CacheLineSize) TPaddedSpinLock
  52. : public TSpinLock
  53. { };
  54. REGISTER_TRACKED_SPIN_LOCK_CLASS(TPaddedSpinLock)
  55. ////////////////////////////////////////////////////////////////////////////////
  56. } // namespace NYT::NThreading
  57. #define SPIN_LOCK_INL_H_
  58. #include "spin_lock-inl.h"
  59. #undef SPIN_LOCK_INL_H_