Line data Source code
1 : // Copyright (c) 2016-2022 The Bitcoin Core developers
2 : // Distributed under the MIT software license, see the accompanying
3 : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4 :
5 : #ifndef BITCOIN_UTIL_THREADINTERRUPT_H
6 : #define BITCOIN_UTIL_THREADINTERRUPT_H
7 :
8 : #include <sync.h>
9 : #include <threadsafety.h>
10 :
11 : #include <atomic>
12 : #include <chrono>
13 : #include <condition_variable>
14 :
15 : /**
16 : * A helper class for interruptible sleeps. Calling operator() will interrupt
17 : * any current sleep, and after that point operator bool() will return true
18 : * until reset.
19 : *
20 : * This class should not be used in a signal handler. It uses thread
21 : * synchronization primitives that are not safe to use with signals. If sending
22 : * an interrupt from a signal handler is necessary, the \ref SignalInterrupt
23 : * class can be used instead.
24 : */
25 :
26 : class CThreadInterrupt
27 : {
28 : public:
29 : using Clock = std::chrono::steady_clock;
30 :
31 : CThreadInterrupt();
32 :
33 625 : virtual ~CThreadInterrupt() = default;
34 :
35 : /// Return true if `operator()()` has been called.
36 : virtual bool interrupted() const;
37 :
38 : /// An alias for `interrupted()`.
39 : virtual explicit operator bool() const;
40 :
41 : /// Interrupt any sleeps. After this `interrupted()` will return `true`.
42 : virtual void operator()() EXCLUSIVE_LOCKS_REQUIRED(!mut);
43 :
44 : /// Reset to an non-interrupted state.
45 : virtual void reset();
46 :
47 : /// Sleep for the given duration.
48 : /// @retval true The time passed.
49 : /// @retval false The sleep was interrupted.
50 : virtual bool sleep_for(Clock::duration rel_time) EXCLUSIVE_LOCKS_REQUIRED(!mut);
51 :
52 : private:
53 : std::condition_variable cond;
54 : Mutex mut;
55 : std::atomic<bool> flag;
56 : };
57 :
58 : #endif // BITCOIN_UTIL_THREADINTERRUPT_H
|