spin_lock-inl.h 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #pragma once
  2. #ifndef SPIN_LOCK_INL_H_
  3. #error "Direct inclusion of this file is not allowed, include spin_lock.h"
  4. // For the sake of sane code completion.
  5. #include "spin_lock.h"
  6. #endif
  7. #undef SPIN_LOCK_INL_H_
  8. #include "spin_wait.h"
  9. #include <library/cpp/yt/assert/assert.h>
  10. namespace NYT::NThreading {
  11. ////////////////////////////////////////////////////////////////////////////////
  12. inline void TSpinLock::Acquire() noexcept
  13. {
  14. if (TryAcquire()) {
  15. return;
  16. }
  17. AcquireSlow();
  18. }
  19. inline void TSpinLock::Release() noexcept
  20. {
  21. #ifdef NDEBUG
  22. Value_.store(UnlockedValue, std::memory_order::release);
  23. #else
  24. YT_ASSERT(Value_.exchange(UnlockedValue, std::memory_order::release) != UnlockedValue);
  25. #endif
  26. NDetail::RecordSpinLockReleased();
  27. }
  28. inline bool TSpinLock::IsLocked() const noexcept
  29. {
  30. return Value_.load(std::memory_order::relaxed) != UnlockedValue;
  31. }
  32. inline bool TSpinLock::TryAcquire() noexcept
  33. {
  34. auto expectedValue = UnlockedValue;
  35. #ifdef YT_ENABLE_SPIN_LOCK_OWNERSHIP_TRACKING
  36. auto newValue = GetSequentialThreadId();
  37. #else
  38. auto newValue = LockedValue;
  39. #endif
  40. bool acquired = Value_.compare_exchange_weak(
  41. expectedValue,
  42. newValue,
  43. std::memory_order::acquire,
  44. std::memory_order::relaxed);
  45. NDetail::RecordSpinLockAcquired(acquired);
  46. return acquired;
  47. }
  48. inline bool TSpinLock::TryAndTryAcquire() noexcept
  49. {
  50. auto value = Value_.load(std::memory_order::relaxed);
  51. #ifdef YT_ENABLE_SPIN_LOCK_OWNERSHIP_TRACKING
  52. YT_ASSERT(value != GetSequentialThreadId());
  53. #endif
  54. if (value != UnlockedValue) {
  55. return false;
  56. }
  57. return TryAcquire();
  58. }
  59. ////////////////////////////////////////////////////////////////////////////////
  60. } // namespace NYT::NThreading