util: move threadinterrupt into util

This commit is contained in:
fanquake
2022-10-11 15:33:22 +08:00
parent c041d8f2c9
commit b89530483d
15 changed files with 18 additions and 16 deletions

View File

@@ -4,11 +4,11 @@
#include <compat/compat.h>
#include <logging.h>
#include <threadinterrupt.h>
#include <tinyformat.h>
#include <util/sock.h>
#include <util/syserror.h>
#include <util/system.h>
#include <util/threadinterrupt.h>
#include <util/time.h>
#include <memory>

View File

@@ -6,7 +6,7 @@
#define BITCOIN_UTIL_SOCK_H
#include <compat/compat.h>
#include <threadinterrupt.h>
#include <util/threadinterrupt.h>
#include <util/time.h>
#include <chrono>

View File

@@ -0,0 +1,35 @@
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2018 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <util/threadinterrupt.h>
#include <sync.h>
CThreadInterrupt::CThreadInterrupt() : flag(false) {}
CThreadInterrupt::operator bool() const
{
return flag.load(std::memory_order_acquire);
}
void CThreadInterrupt::reset()
{
flag.store(false, std::memory_order_release);
}
void CThreadInterrupt::operator()()
{
{
LOCK(mut);
flag.store(true, std::memory_order_release);
}
cond.notify_all();
}
bool CThreadInterrupt::sleep_for(Clock::duration rel_time)
{
WAIT_LOCK(mut, lock);
return !cond.wait_for(lock, rel_time, [this]() { return flag.load(std::memory_order_acquire); });
}

View File

@@ -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