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