aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/coroutine/util/pipeevent.h
blob: 059f2a34d9a6d6985110e752ba656f27047c9dcc (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
84
85
86
87
88
89
90
91
92
93
#pragma once

#include <library/cpp/coroutine/engine/events.h>
#include <library/cpp/coroutine/engine/impl.h>
#include <library/cpp/coroutine/engine/network.h>

#include <util/network/socket.h>
#include <library/cpp/deprecated/atomic/atomic.h>
#include <util/system/pipe.h>

// TPipeEvent and TPipeSemaphore try to minimize number of coroutines reading from same pipe
// because its actually quite expensive with >1000 coroutines waiting on same event/semaphore

// Using this class you can block in coroutine on waiting
// a signal from outer thread.
// Usual thread synchronization primitives are not appropriate
// because they will block all coroutines in single thread.
class TPipeEvent {
public:
    explicit TPipeEvent()
        : Signaled(0)
        , NumWaiting(0)
    {
        TPipeHandle::Pipe(SignalRecvPipe, SignalSendPipe);
        SetNonBlock(SignalRecvPipe);
        SetNonBlock(SignalSendPipe);
    }

    void Signal() {
        if (AtomicCas(&Signaled, 1, 0)) {
            char tmp = 1;
            SignalSendPipe.Write(&tmp, 1);
        }
    }

    void Wait(TCont* cont) {
        if (++NumWaiting > 1) {
            ToWake.WaitI(cont);
        }
        char tmp;
        NCoro::ReadI(cont, SignalRecvPipe, &tmp, 1).Checked();
        AtomicSet(Signaled, 0);
        if (--NumWaiting > 0) {
            ToWake.Signal();
        }
    }

private:
    TAtomic Signaled;
    size_t NumWaiting;
    TContWaitQueue ToWake;
    TPipeHandle SignalRecvPipe;
    TPipeHandle SignalSendPipe;
};

class TPipeSemaphore {
public:
    explicit TPipeSemaphore()
        : Value(0)
        , NumWaiting(0)
    {
        TPipeHandle::Pipe(SignalRecvPipe, SignalSendPipe);
        SetNonBlock(SignalRecvPipe);
        SetNonBlock(SignalSendPipe);
    }

    void Inc() {
        if (AtomicIncrement(Value) <= 0) {
            char tmp = 1;
            SignalSendPipe.Write(&tmp, 1);
        }
    }

    void Dec(TCont* cont) {
        if (AtomicDecrement(Value) < 0) {
            if (++NumWaiting > 1) {
                ToWake.WaitI(cont);
            }
            char tmp;
            NCoro::ReadI(cont, SignalRecvPipe, &tmp, 1).Checked();
            if (--NumWaiting > 0) {
                ToWake.Signal();
            }
        }
    }

private:
    TAtomic Value;
    size_t NumWaiting;
    TContWaitQueue ToWake;
    TPipeHandle SignalRecvPipe;
    TPipeHandle SignalSendPipe;
};