1 // Copyright (c) 2023-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_SIGNALINTERRUPT_H
6 #define BITCOIN_UTIL_SIGNALINTERRUPT_H
7 8 #ifdef WIN32
9 #include <condition_variable>
10 #include <mutex>
11 #else
12 #include <util/tokenpipe.h>
13 #endif
14 15 #include <atomic>
16 17 namespace util {
18 /**
19 * Helper class that manages an interrupt flag, and allows a thread or
20 * signal to interrupt another thread.
21 *
22 * This class is safe to be used in a signal handler. If sending an interrupt
23 * from a signal handler is not necessary, the more lightweight \ref
24 * CThreadInterrupt class can be used instead.
25 */
26 27 class SignalInterrupt
28 {
29 public:
30 SignalInterrupt();
31 explicit operator bool() const;
32 [[nodiscard]] bool operator()();
33 [[nodiscard]] bool reset();
34 [[nodiscard]] bool wait();
35 36 private:
37 std::atomic<bool> m_flag;
38 39 #ifndef WIN32
40 // On UNIX-like operating systems use the self-pipe trick.
41 TokenPipeEnd m_pipe_r;
42 TokenPipeEnd m_pipe_w;
43 #else
44 // On windows use a condition variable, since we don't have any signals there
45 std::mutex m_mutex;
46 std::condition_variable m_cv;
47 #endif
48 };
49 } // namespace util
50 51 #endif // BITCOIN_UTIL_SIGNALINTERRUPT_H
52