1#pragma once
2#include <atomic>
3
4
5namespace DB
6{
7
8class SimpleActionLock;
9
10
11/// Similar to ActionBlocker, but without weak_ptr magic
12class SimpleActionBlocker
13{
14 using Counter = std::atomic<int>;
15 Counter counter = 0;
16
17public:
18
19 SimpleActionBlocker() = default;
20
21 bool isCancelled() const { return counter > 0; }
22
23 /// Temporarily blocks corresponding actions (while the returned object is alive)
24 friend class SimpleActionLock;
25 inline SimpleActionLock cancel();
26
27 /// Cancel the actions forever.
28 void cancelForever() { ++counter; }
29};
30
31
32/// Blocks related action while a SimpleActionLock instance exists
33class SimpleActionLock
34{
35 SimpleActionBlocker * block = nullptr;
36
37public:
38
39 SimpleActionLock() = default;
40
41 explicit SimpleActionLock(SimpleActionBlocker & block_) : block(&block_)
42 {
43 ++block->counter;
44 }
45
46 SimpleActionLock(const SimpleActionLock &) = delete;
47
48 SimpleActionLock(SimpleActionLock && rhs) noexcept
49 {
50 *this = std::move(rhs);
51 }
52
53 SimpleActionLock & operator=(const SimpleActionLock &) = delete;
54
55 SimpleActionLock & operator=(SimpleActionLock && rhs) noexcept
56 {
57 if (block)
58 --block->counter;
59
60 block = rhs.block;
61 rhs.block = nullptr;
62
63 return *this;
64 }
65
66 ~SimpleActionLock()
67 {
68 if (block)
69 --block->counter;
70 }
71};
72
73
74SimpleActionLock SimpleActionBlocker::cancel()
75{
76 return SimpleActionLock(*this);
77}
78
79}
80