aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/yt/threading/spin_lock-inl.h
blob: 515842f9cc23542786d27afe2d800a09c5644e17 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#pragma once
#ifndef SPIN_LOCK_INL_H_
#error "Direct inclusion of this file is not allowed, include spin_lock.h"
// For the sake of sane code completion.
#include "spin_lock.h"
#endif
#undef SPIN_LOCK_INL_H_

#include "spin_wait.h"

#include <library/cpp/yt/assert/assert.h>

namespace NYT::NThreading {

////////////////////////////////////////////////////////////////////////////////

inline void TSpinLock::Acquire() noexcept
{
    if (TryAcquire()) {
        return;
    }

    AcquireSlow();
}

inline void TSpinLock::Release() noexcept
{
#ifdef NDEBUG
    Value_.store(UnlockedValue, std::memory_order_release);
#else
    YT_ASSERT(Value_.exchange(UnlockedValue, std::memory_order_release) != UnlockedValue);
#endif
}

inline bool TSpinLock::IsLocked() const noexcept
{
    return Value_.load() != UnlockedValue;
}

inline bool TSpinLock::TryAcquire() noexcept
{
    auto expectedValue = UnlockedValue;
#ifdef YT_ENABLE_SPIN_LOCK_OWNERSHIP_TRACKING
    auto newValue = GetSequentialThreadId();
#else
    auto newValue = LockedValue;
#endif
    return Value_.compare_exchange_weak(expectedValue, newValue);
}

inline bool TSpinLock::TryAndTryAcquire() noexcept
{
    auto value = Value_.load(std::memory_order_relaxed);
#ifdef YT_ENABLE_SPIN_LOCK_OWNERSHIP_TRACKING
    YT_ASSERT(value != GetSequentialThreadId());
#endif
    if (value != UnlockedValue) {
        return false;
    }
    return TryAcquire();
}

////////////////////////////////////////////////////////////////////////////////

} // namespace NYT::NThreading