aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/yt/threading/recursive_spin_lock-inl.h
blob: aca27ba1cfeca2b955247daa2538e4a618d2d6d2 (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
67
68
69
70
71
72
73
74
75
#ifndef RECURSIVE_SPIN_LOCK_INL_H_
#error "Direct inclusion of this file is not allowed, include recursive_spinlock.h"
// For the sake of sane code completion.
#include "recursive_spin_lock.h"
#endif
#undef RECURSIVE_SPIN_LOCK_INL_H_

#include "spin_wait.h"

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

namespace NYT::NThreading {

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

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

inline bool TRecursiveSpinLock::TryAcquire() noexcept
{
    auto currentThreadId = GetSequentialThreadId();
    auto oldValue = Value_.load();
    auto oldRecursionDepth = oldValue & RecursionDepthMask;
    if (oldRecursionDepth > 0 && (oldValue >> ThreadIdShift) != currentThreadId) {
        return false;
    }
    auto newValue = (oldRecursionDepth + 1) | (static_cast<TValue>(currentThreadId) << ThreadIdShift);

    bool acquired = Value_.compare_exchange_weak(oldValue, newValue);
    NDetail::RecordSpinLockAcquired(acquired);
    return acquired;
}

inline void TRecursiveSpinLock::Release() noexcept
{
#ifndef NDEBUG
    auto value = Value_.load();
    YT_ASSERT((value & RecursionDepthMask) > 0);
    YT_ASSERT((value >> ThreadIdShift) == GetSequentialThreadId());
#endif
    --Value_;
    NDetail::RecordSpinLockReleased();
}

inline bool TRecursiveSpinLock::IsLocked() const noexcept
{
    auto value = Value_.load();
    return (value & RecursionDepthMask) > 0;
}

inline bool TRecursiveSpinLock::IsLockedByCurrentThread() const noexcept
{
    auto value = Value_.load();
    return (value & RecursionDepthMask) > 0 && (value >> ThreadIdShift) == GetSequentialThreadId();
}

inline bool TRecursiveSpinLock::TryAndTryAcquire() noexcept
{
    auto value = Value_.load(std::memory_order::relaxed);
    auto recursionDepth = value & RecursionDepthMask;
    if (recursionDepth > 0 && (value >> ThreadIdShift) != GetSequentialThreadId()) {
        return false;
    }
    return TryAcquire();
}

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

} // namespace NYT::NThreading