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


namespace DB
{

/// An atomic variable that is used to block and interrupt certain actions.
/// If it is not zero then actions related with it should be considered as interrupted.
/// Uses shared_ptr and the lock uses weak_ptr to be able to "hold" a lock when an object with blocker has already died.
class ActionBlocker
{
public:
    ActionBlocker() : counter(std::make_shared<Counter>(0)) {}

    bool isCancelled() const { return *counter > 0; }

    /// Temporarily blocks corresponding actions (while the returned object is alive)
    friend class ActionLock;
    ActionLock cancel() { return ActionLock(*this); }

    /// Cancel the actions forever.
    void cancelForever() { ++(*counter); }

    /// Returns reference to counter to allow to watch on it directly.
    const std::atomic<int> & getCounter() const { return *counter; }

private:
    using Counter = std::atomic<int>;
    using CounterPtr = std::shared_ptr<Counter>;

    CounterPtr counter;
};


}