util: Add SignalInterrupt class and use in shutdown.cpp

This change helps generalize shutdown code so an interrupt can be
provided to libbitcoinkernel callers. This may also be useful to
eventually de-globalize all of the shutdown code.

Co-authored-by: Russell Yanofsky <russ@yanofsky.org>
Co-authored-by: TheCharlatan <seb.kung@gmail.com>
This commit is contained in:
TheCharlatan
2023-06-01 16:53:33 -04:00
parent d9c7c2fd3e
commit e2d680a32d
10 changed files with 175 additions and 65 deletions

View File

@@ -0,0 +1,52 @@
// Copyright (c) 2023 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_SIGNALINTERRUPT_H
#define BITCOIN_UTIL_SIGNALINTERRUPT_H
#ifdef WIN32
#include <condition_variable>
#include <mutex>
#else
#include <util/tokenpipe.h>
#endif
#include <atomic>
#include <cstdlib>
namespace util {
/**
* Helper class that manages an interrupt flag, and allows a thread or
* signal to interrupt another thread.
*
* This class is safe to be used in a signal handler. If sending an interrupt
* from a signal handler is not necessary, the more lightweight \ref
* CThreadInterrupt class can be used instead.
*/
class SignalInterrupt
{
public:
SignalInterrupt();
explicit operator bool() const;
void operator()();
void reset();
void wait();
private:
std::atomic<bool> m_flag;
#ifndef WIN32
// On UNIX-like operating systems use the self-pipe trick.
TokenPipeEnd m_pipe_r;
TokenPipeEnd m_pipe_w;
#else
// On windows use a condition variable, since we don't have any signals there
std::mutex m_mutex;
std::condition_variable m_cv;
#endif
};
} // namespace util
#endif // BITCOIN_UTIL_SIGNALINTERRUPT_H