aboutsummaryrefslogtreecommitdiff
path: root/src/util/threadinterrupt.h
diff options
context:
space:
mode:
Diffstat (limited to 'src/util/threadinterrupt.h')
-rw-r--r--src/util/threadinterrupt.h36
1 files changed, 36 insertions, 0 deletions
diff --git a/src/util/threadinterrupt.h b/src/util/threadinterrupt.h
new file mode 100644
index 0000000000..d95cbb9aba
--- /dev/null
+++ b/src/util/threadinterrupt.h
@@ -0,0 +1,36 @@
+// Copyright (c) 2016-2021 The Bitcoin Core developers
+// Distributed under the MIT software license, see the accompanying
+// file COPYING or http://www.opensource.org/licenses/mit-license.php.
+
+#ifndef BITCOIN_UTIL_THREADINTERRUPT_H
+#define BITCOIN_UTIL_THREADINTERRUPT_H
+
+#include <sync.h>
+#include <threadsafety.h>
+
+#include <atomic>
+#include <chrono>
+#include <condition_variable>
+
+/*
+ A helper class for interruptible sleeps. Calling operator() will interrupt
+ any current sleep, and after that point operator bool() will return true
+ until reset.
+*/
+class CThreadInterrupt
+{
+public:
+ using Clock = std::chrono::steady_clock;
+ CThreadInterrupt();
+ explicit operator bool() const;
+ void operator()() EXCLUSIVE_LOCKS_REQUIRED(!mut);
+ void reset();
+ bool sleep_for(Clock::duration rel_time) EXCLUSIVE_LOCKS_REQUIRED(!mut);
+
+private:
+ std::condition_variable cond;
+ Mutex mut;
+ std::atomic<bool> flag;
+};
+
+#endif // BITCOIN_UTIL_THREADINTERRUPT_H