aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/messagebus/remote_client_session_semaphore.cpp
blob: fce7349a36d11fed9f2ea8ba4677e469c2e8fadd (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
#include "remote_client_session_semaphore.h"

#include <util/stream/output.h>
#include <util/system/yassert.h>

using namespace NBus;
using namespace NBus::NPrivate;

TRemoteClientSessionSemaphore::TRemoteClientSessionSemaphore(TAtomicBase limit, const char* name)
    : Name(name)
    , Limit(limit)
    , Current(0)
    , StopSignal(0)
{
    Y_VERIFY(limit > 0, "limit must be > 0");
    Y_UNUSED(Name);
}

TRemoteClientSessionSemaphore::~TRemoteClientSessionSemaphore() { 
    Y_VERIFY(AtomicGet(Current) == 0);
}

bool TRemoteClientSessionSemaphore::TryAcquire() {
    if (!TryWait()) {
        return false;
    }

    AtomicIncrement(Current);
    return true;
}

bool TRemoteClientSessionSemaphore::TryWait() {
    if (AtomicGet(Current) < Limit)
        return true;
    if (Y_UNLIKELY(AtomicGet(StopSignal)))
        return true;
    return false;
}

void TRemoteClientSessionSemaphore::Acquire() {
    Wait();

    Increment();
}

void TRemoteClientSessionSemaphore::Increment() {
    IncrementMultiple(1);
}

void TRemoteClientSessionSemaphore::IncrementMultiple(TAtomicBase count) {
    AtomicAdd(Current, count);
    Updated();
}

void TRemoteClientSessionSemaphore::Release() {
    ReleaseMultiple(1);
}

void TRemoteClientSessionSemaphore::ReleaseMultiple(TAtomicBase count) {
    AtomicSub(Current, count);
    Updated();
}

void TRemoteClientSessionSemaphore::Stop() {
    AtomicSet(StopSignal, 1);
    Updated();
}