aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/actors/util/ticket_lock.h
blob: 30355c3390dfe6822750be0201212c75b03a5784 (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
#pragma once

#include "intrinsics.h"
#include <util/system/guard.h>
#include <util/system/yassert.h>

class TTicketLock : TNonCopyable {
    ui32 TicketIn;
    ui32 TicketOut;

public:
    TTicketLock()
        : TicketIn(0)
        , TicketOut(0)
    {
    }

    void Release() noexcept {
        AtomicUi32Increment(&TicketOut);
    }

    ui32 Acquire() noexcept {
        ui32 revolves = 0;
        const ui32 ticket = AtomicUi32Increment(&TicketIn) - 1;
        while (ticket != AtomicLoad(&TicketOut)) {
            Y_DEBUG_ABORT_UNLESS(ticket >= AtomicLoad(&TicketOut));
            SpinLockPause();
            ++revolves;
        }
        return revolves;
    }

    bool TryAcquire() noexcept {
        const ui32 x = AtomicLoad(&TicketOut);
        if (x == AtomicLoad(&TicketIn) && AtomicUi32Cas(&TicketIn, x + 1, x))
            return true;
        else
            return false;
    }

    bool IsLocked() noexcept {
        const ui32 ticketIn = AtomicLoad(&TicketIn);
        const ui32 ticketOut = AtomicLoad(&TicketOut);
        return (ticketIn != ticketOut);
    }

    typedef ::TGuard<TTicketLock> TGuard;
};