ClickHouse/dbms/src/Common/ActionBlocker.h

39 lines
1.0 KiB
C++
Raw Normal View History

#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.
2017-10-12 20:34:01 +00:00
class ActionBlocker
{
2017-10-12 20:34:01 +00:00
public:
ActionBlocker() : counter(std::make_shared<Counter>(0)) {}
bool isCancelled() const { return *counter > 0; }
2017-10-12 20:15:39 +00:00
/// Temporarily blocks corresponding actions (while the returned object is alive)
friend class ActionLock;
ActionLock cancel() { return ActionLock(*this); }
2017-10-12 20:34:01 +00:00
/// Cancel the actions forever.
void cancelForever() { ++(*counter); }
2017-10-12 20:34:01 +00:00
/// 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;
};
}