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

#include <util/system/yassert.h>

class TExtraRef {
    TAtomic Holds;

public:
    TExtraRef()
        : Holds(false)
    {
    }
    ~TExtraRef() {
        Y_VERIFY(!Holds);
    }

    template <typename TThis>
    void Retain(TThis* thiz) {
        if (AtomicGet(Holds)) {
            return;
        }
        if (AtomicCas(&Holds, 1, 0)) {
            thiz->Ref();
        }
    }

    template <typename TThis>
    void Release(TThis* thiz) {
        if (!AtomicGet(Holds)) {
            return;
        }
        if (AtomicCas(&Holds, 0, 1)) {
            thiz->UnRef();
        }
    }
};