Inside Bitcoin
Opening the selected file…
Inside Bitcoin
Opening the selected file…
The code behind the network, with room to understand it.
Release published 2026-10-28 · Snapshot fetched 2026-11-01. Latest stable release at fetch time; development branches and Git history are excluded. Only the selected code window and visible folders load here.
1// Copyright (c) 2015-present The Bitcoin Core developers2// Distributed under the MIT software license, see the accompanying3// file COPYING or http://www.opensource.org/licenses/mit-license.php.5#ifndef BITCOIN_SCHEDULER_H6#define BITCOIN_SCHEDULER_H8#include <attributes.h>9#include <sync.h>10#include <util/task_runner.h>12#include <chrono>13#include <condition_variable>14#include <cstddef>15#include <functional>16#include <list>17#include <map>18#include <thread>19#include <utility>21/**22* Simple class for background tasks that should be run23* periodically or once "after a while"24*25* Usage:26*27* CScheduler* s = new CScheduler();28* s->scheduleFromNow(doSomething, std::chrono::milliseconds{11}); // Assuming a: void doSomething() { }29* s->scheduleFromNow([=] { this->func(argument); }, std::chrono::milliseconds{3});30* std::thread* t = new std::thread([&] { s->serviceQueue(); });31*32* ... then at program shutdown, make sure to call stop() to clean up the thread(s) running serviceQueue:33* s->stop();34* t->join();35* delete t;36* delete s; // Must be done after thread is interrupted/joined.37*/38class CScheduler39{40public:41CScheduler();42~CScheduler();44std::thread m_service_thread;46typedef std::function<void()> Function;48/** Call func at/after time t */49void schedule(Function f, std::chrono::steady_clock::time_point t) EXCLUSIVE_LOCKS_REQUIRED(!newTaskMutex);51/** Call f once after the delta has passed */52void scheduleFromNow(Function f, std::chrono::milliseconds delta) EXCLUSIVE_LOCKS_REQUIRED(!newTaskMutex)53{54schedule(std::move(f), std::chrono::steady_clock::now() + delta);55}57/**58* Repeat f until the scheduler is stopped. First run is after delta has passed once.59*60* The timing is not exact: Every time f is finished, it is rescheduled to run again after delta. If you need more61* accurate scheduling, don't use this method.62*/63void scheduleEvery(Function f, std::chrono::milliseconds delta) EXCLUSIVE_LOCKS_REQUIRED(!newTaskMutex);65/**66* Mock the scheduler to fast forward in time.67* Iterates through items on taskQueue and reschedules them68* to be delta_seconds sooner.69*/70void MockForward(std::chrono::seconds delta_seconds) EXCLUSIVE_LOCKS_REQUIRED(!newTaskMutex);72/**73* \anchor scheduler74* Services the queue 'forever'. Should be run in a thread.75*/76void serviceQueue() EXCLUSIVE_LOCKS_REQUIRED(!newTaskMutex);78/** Tell any threads running serviceQueue to stop as soon as the current task is done */79void stop() EXCLUSIVE_LOCKS_REQUIRED(!newTaskMutex)80{81WITH_LOCK(newTaskMutex, stopRequested = true);82newTaskScheduled.notify_all();83if (m_service_thread.joinable()) m_service_thread.join();84}85/** Tell any threads running serviceQueue to stop when there is no work left to be done */86void StopWhenDrained() EXCLUSIVE_LOCKS_REQUIRED(!newTaskMutex)87{88WITH_LOCK(newTaskMutex, stopWhenEmpty = true);89newTaskScheduled.notify_all();90if (m_service_thread.joinable()) m_service_thread.join();91}93/**94* Returns number of tasks waiting to be serviced,95* and first and last task times96*/97size_t getQueueInfo(std::chrono::steady_clock::time_point& first,98std::chrono::steady_clock::time_point& last) const99EXCLUSIVE_LOCKS_REQUIRED(!newTaskMutex);101/** Returns true if there are threads actively running in serviceQueue() */102bool AreThreadsServicingQueue() const EXCLUSIVE_LOCKS_REQUIRED(!newTaskMutex);104private:105mutable Mutex newTaskMutex;106std::condition_variable newTaskScheduled;107std::multimap<std::chrono::steady_clock::time_point, Function> taskQueue GUARDED_BY(newTaskMutex);108int nThreadsServicingQueue GUARDED_BY(newTaskMutex){0};109bool stopRequested GUARDED_BY(newTaskMutex){false};110bool stopWhenEmpty GUARDED_BY(newTaskMutex){false};111bool shouldStop() const EXCLUSIVE_LOCKS_REQUIRED(newTaskMutex) { return stopRequested || (stopWhenEmpty && taskQueue.empty()); }112};114/**115* Class used by CScheduler clients which may schedule multiple jobs116* which are required to be run serially. Jobs may not be run on the117* same thread, but no two jobs will be executed118* at the same time and memory will be release-acquire consistent119* (the scheduler will internally do an acquire before invoking a callback120* as well as a release at the end). In practice this means that a callback121* B() will be able to observe all of the effects of callback A() which executed122* before it.123*/124class SerialTaskRunner : public util::TaskRunnerInterface125{126private:127CScheduler& m_scheduler;129Mutex m_callbacks_mutex;131// We are not allowed to assume the scheduler only runs in one thread,132// but must ensure all callbacks happen in-order, so we end up creating133// our own queue here :(134std::list<std::function<void()>> m_callbacks_pending GUARDED_BY(m_callbacks_mutex);135bool m_are_callbacks_running GUARDED_BY(m_callbacks_mutex) = false;137void MaybeScheduleProcessQueue() EXCLUSIVE_LOCKS_REQUIRED(!m_callbacks_mutex);138void ProcessQueue() EXCLUSIVE_LOCKS_REQUIRED(!m_callbacks_mutex);140public:141explicit SerialTaskRunner(CScheduler& scheduler LIFETIMEBOUND) : m_scheduler{scheduler} {}143/**144* Add a callback to be executed. Callbacks are executed serially145* and memory is release-acquire consistent between callback executions.146* Practically, this means that callbacks can behave as if they are executed147* in order by a single thread.148*/149void insert(std::function<void()> func) override EXCLUSIVE_LOCKS_REQUIRED(!m_callbacks_mutex);151/**152* Processes all remaining queue members on the calling thread, blocking until queue is empty153* Must be called after the CScheduler has no remaining processing threads!154*/155void flush() override EXCLUSIVE_LOCKS_REQUIRED(!m_callbacks_mutex);157size_t size() override EXCLUSIVE_LOCKS_REQUIRED(!m_callbacks_mutex);158};160#endif // BITCOIN_SCHEDULER_H