aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/threading/equeue/equeue.cpp
blob: aaec19daa670496d06ca85c8b9dffddf1e9ed957 (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
#include "equeue.h" 
 
TElasticQueue::TElasticQueue(THolder<IThreadPool> slaveQueue) 
    : SlaveQueue_(std::move(slaveQueue)) 
{ 
} 
 
size_t TElasticQueue::ObjectCount() const { 
    return (size_t)AtomicGet(ObjectCount_); 
} 
 
bool TElasticQueue::TryIncCounter() { 
    if ((size_t)AtomicIncrement(GuardCount_) > MaxQueueSize_) { 
        AtomicDecrement(GuardCount_); 
        return false; 
    } 
 
    return true; 
} 
 
 
 
class TElasticQueue::TDecrementingWrapper: TNonCopyable, public IObjectInQueue { 
public: 
    TDecrementingWrapper(IObjectInQueue* realObject, TElasticQueue* queue) 
        : RealObject_(realObject) 
        , Queue_(queue) 
    { 
        AtomicIncrement(Queue_->ObjectCount_); 
    } 
 
    ~TDecrementingWrapper() override {
        AtomicDecrement(Queue_->ObjectCount_); 
        AtomicDecrement(Queue_->GuardCount_); 
    } 
private: 
    void Process(void *tsr) override { 
        THolder<TDecrementingWrapper> self(this); 
        RealObject_->Process(tsr); 
    } 
private: 
    IObjectInQueue* const RealObject_; 
    TElasticQueue* const Queue_; 
}; 
 
 
 
bool TElasticQueue::Add(IObjectInQueue* obj) { 
    if (!TryIncCounter()) { 
        return false; 
    } 
 
    THolder<TDecrementingWrapper> wrapper; 
    try { 
        wrapper.Reset(new TDecrementingWrapper(obj, this)); 
    } catch (...) { 
        AtomicDecrement(GuardCount_); 
        throw; 
    } 
 
    if (SlaveQueue_->Add(wrapper.Get())) { 
        Y_UNUSED(wrapper.Release());
        return true; 
    } else { 
        return false; 
    } 
} 
 
void TElasticQueue::Start(size_t threadCount, size_t maxQueueSize) { 
    MaxQueueSize_ = maxQueueSize; 
    SlaveQueue_->Start(threadCount, maxQueueSize); 
} 
 
void TElasticQueue::Stop() noexcept {
    return SlaveQueue_->Stop(); 
} 
 
size_t TElasticQueue::Size() const noexcept {
    return SlaveQueue_->Size(); 
}