aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/clickhouse/src/Common/ActionLock.h
blob: aeede564e1181bfae2439a5f7d8016e20e5fff1a (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
#pragma once
#include <memory>
#include <atomic>


namespace DB
{

class ActionBlocker;
using StorageActionBlockType = size_t;

/// Blocks related action while a ActionLock instance exists
/// ActionBlocker could be destroyed before the lock, in this case ActionLock will safely do nothing in its destructor
class ActionLock
{
public:

    ActionLock() = default;

    explicit ActionLock(const ActionBlocker & blocker);

    ActionLock(ActionLock && other) noexcept;
    ActionLock & operator=(ActionLock && other) noexcept;

    ActionLock(const ActionLock & other) = delete;
    ActionLock & operator=(const ActionLock & other) = delete;

    bool expired() const
    {
        return counter_ptr.expired();
    }

    ~ActionLock()
    {
        if (auto counter = counter_ptr.lock())
            --(*counter);
    }

private:
    using Counter = std::atomic<int>;
    using CounterWeakPtr = std::weak_ptr<Counter>;

    CounterWeakPtr counter_ptr;
};

}