aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/yt/threading/spin_lock.h
blob: b8277ebc8d9f4b351fdefebeb93400b1adb6b1fe (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
76
77
78
79
80
81
82
83
#pragma once

#include "public.h"
#include "spin_lock_base.h"
#include "spin_lock_count.h"

#include <library/cpp/yt/misc/port.h>

#include <library/cpp/yt/system/thread_id.h>

#include <library/cpp/yt/memory/public.h>

#include <util/system/src_location.h>
#include <util/system/types.h>

#include <atomic>

namespace NYT::NThreading {

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

//! A slightly modified version of TAdaptiveLock.
/*!
 *  The lock is unfair.
 */
class TSpinLock
    : public TSpinLockBase
{
public:
    using TSpinLockBase::TSpinLockBase;

    //! Acquires the lock.
    void Acquire() noexcept;

    //! Tries acquiring the lock.
    //! Returns |true| on success.
    bool TryAcquire() noexcept;

    //! Releases the lock.
    void Release() noexcept;

    //! Returns true if the lock is taken.
    /*!
     *  This is inherently racy.
     *  Only use for debugging and diagnostic purposes.
     */
    bool IsLocked() const noexcept;

private:
#ifdef YT_ENABLE_SPIN_LOCK_OWNERSHIP_TRACKING
    using TValue = TSequentialThreadId;
    static constexpr TValue UnlockedValue = InvalidSequentialThreadId;
#else
    using TValue = ui32;
    static constexpr TValue UnlockedValue = 0;
    static constexpr TValue LockedValue = 1;
#endif

    std::atomic<TValue> Value_ = UnlockedValue;

    bool TryAndTryAcquire() noexcept;

    void AcquireSlow() noexcept;
};

REGISTER_TRACKED_SPIN_LOCK_CLASS(TSpinLock)

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

//! A variant of TSpinLock occupying the whole cache line.
class alignas(CacheLineSize) TPaddedSpinLock
    : public TSpinLock
{ };

REGISTER_TRACKED_SPIN_LOCK_CLASS(TPaddedSpinLock)

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

} // namespace NYT::NThreading

#define SPIN_LOCK_INL_H_
#include "spin_lock-inl.h"
#undef SPIN_LOCK_INL_H_