aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/messagebus/latch.h
blob: b519e5509c9c00c795599708398d835e2c79180f (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
#pragma once

#include <library/cpp/deprecated/atomic/atomic.h>

#include <util/system/condvar.h>
#include <util/system/mutex.h>

class TLatch {
private:
    // 0 for unlocked, 1 for locked
    TAtomic Locked;
    TMutex Mutex;
    TCondVar CondVar;

public:
    TLatch()
        : Locked(0)
    {
    }

    void Wait() {
        // optimistic path
        if (AtomicGet(Locked) == 0) {
            return;
        }

        TGuard<TMutex> guard(Mutex);
        while (AtomicGet(Locked) == 1) {
            CondVar.WaitI(Mutex);
        }
    }

    bool TryWait() {
        return AtomicGet(Locked) == 0;
    }

    void Unlock() {
        // optimistic path
        if (AtomicGet(Locked) == 0) {
            return;
        }

        TGuard<TMutex> guard(Mutex);
        AtomicSet(Locked, 0);
        CondVar.BroadCast();
    }

    void Lock() {
        AtomicSet(Locked, 1);
    }

    bool IsLocked() {
        return AtomicGet(Locked);
    }
};