blob: fa4cabad3cd86bf16762d8e7c544d33f9c93d3cc (
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/threading/future/future.h>
#include <util/system/spinlock.h>
#include <util/generic/ptr.h>
#include <list>
#include <functional>
namespace NThreading {
class TAsyncSemaphore: public TThrRefBase {
public:
    using TPtr = TIntrusivePtr<TAsyncSemaphore>;
    class TAutoRelease {
    public:
        TAutoRelease(TAsyncSemaphore::TPtr sem)
            : Sem(std::move(sem))
        {
        }
        TAutoRelease(TAutoRelease&& other)
            : Sem(std::move(other.Sem))
        {
        }
        ~TAutoRelease();
        std::function<void (const TFuture<void>&)> DeferRelease();
    private:
        TAsyncSemaphore::TPtr Sem;
    };
    static TPtr Make(size_t count);
    TFuture<TPtr> AcquireAsync();
    void Release();
    void Cancel();
    TAutoRelease MakeAutoRelease() {
        return {this};
    }
private:
    TAsyncSemaphore(size_t count);
private:
    size_t Count_;
    bool Cancelled_ = false;
    TAdaptiveLock Lock_;
    std::list<TPromise<TPtr>> Promises_;
};
} // namespace NThreading
 |