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) 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#include <common/system.h>6#include <logging.h>7#include <random.h>8#include <test/util/common.h>9#include <util/string.h>10#include <util/threadpool.h>11#include <util/time.h>13#include <boost/test/unit_test.hpp>15#include <array>16#include <functional>17#include <latch>18#include <ranges>19#include <semaphore>21// General test values22int NUM_WORKERS_DEFAULT = 0;23constexpr char POOL_NAME[] = "test";24constexpr auto TEST_WAIT_TIMEOUT = 120s;26struct ThreadPoolFixture {27ThreadPoolFixture() {28NUM_WORKERS_DEFAULT = FastRandomContext().randrange(GetNumCores()) + 1;29LogInfo("thread pool workers count: %d", NUM_WORKERS_DEFAULT);30}31};33// Test Cases Overview34// 0) Submit task to a non-started pool.35// 1) Submit tasks and verify completion.36// 2) Maintain all threads busy except one.37// 3) Wait for work to finish.38// 4) Wait for result object.39// 5) The task throws an exception, catch must be done in the consumer side.40// 6) Busy workers, help them by processing tasks externally.41// 7) Recursive submission of tasks.42// 8) Submit task when all threads are busy, stop pool and verify task gets executed.43// 9) Congestion test; create more workers than available cores.44// 10) Ensure Interrupt() prevents further submissions.45// 11) Start() must not cause a deadlock when called during Stop().46// 12) Ensure queued tasks complete after Interrupt().47// 13) Ensure the Stop() calling thread helps drain the queue.48// 14) Submit range of tasks in one lock acquisition.49BOOST_FIXTURE_TEST_SUITE(threadpool_tests, ThreadPoolFixture)51#define WAIT_FOR(futures) \52do { \53for (const auto& f : futures) { \54BOOST_REQUIRE(f.wait_for(TEST_WAIT_TIMEOUT) == std::future_status::ready); \55} \56} while (0)58// Helper to unwrap a valid pool submission59template <typename F>60[[nodiscard]] auto Submit(ThreadPool& pool, F&& fn)61{62return std::move(*Assert(pool.Submit(std::forward<F>(fn))));63}65// Block a number of worker threads by submitting tasks that wait on `release_sem`.66// Returns the futures of the blocking tasks, ensuring all have started and are waiting.67std::vector<std::future<void>> BlockWorkers(ThreadPool& threadPool, std::counting_semaphore<>& release_sem, size_t num_of_threads_to_block)68{69assert(threadPool.WorkersCount() >= num_of_threads_to_block);70std::latch ready{static_cast<std::ptrdiff_t>(num_of_threads_to_block)};71std::vector<std::future<void>> blocking_tasks(num_of_threads_to_block);72for (auto& f : blocking_tasks) f = Submit(threadPool, [&] {73ready.count_down();74release_sem.acquire();75});76ready.wait();77return blocking_tasks;78}80// Test 0, submit task to a non-started, interrupted, or stopped pool81BOOST_AUTO_TEST_CASE(submit_fails_with_correct_error)82{83ThreadPool threadPool(POOL_NAME);84const auto fn_empty = [&] {};86// Never started: Inactive87auto res = threadPool.Submit(fn_empty);88BOOST_CHECK(!res);89BOOST_CHECK_EQUAL(SubmitErrorString(res.error()), "No active workers");91// Interrupted (workers still alive): Interrupted, and Start() must be rejected too92std::counting_semaphore<> blocker(0);93threadPool.Start(NUM_WORKERS_DEFAULT);94const auto blocking_tasks = BlockWorkers(threadPool, blocker, NUM_WORKERS_DEFAULT);95threadPool.Interrupt();96res = threadPool.Submit(fn_empty);97BOOST_CHECK(!res);98BOOST_CHECK_EQUAL(SubmitErrorString(res.error()), "Interrupted");99BOOST_CHECK_EXCEPTION(threadPool.Start(NUM_WORKERS_DEFAULT), std::runtime_error, HasReason("Thread pool has been interrupted or is stopping"));100blocker.release(NUM_WORKERS_DEFAULT);101WAIT_FOR(blocking_tasks);103// Interrupted then stopped: Inactive104threadPool.Stop();105res = threadPool.Submit(fn_empty);106BOOST_CHECK(!res);107BOOST_CHECK_EQUAL(SubmitErrorString(res.error()), "No active workers");109// Started then stopped: Inactive110threadPool.Start(NUM_WORKERS_DEFAULT);111threadPool.Stop();112res = threadPool.Submit(fn_empty);113BOOST_CHECK(!res);114BOOST_CHECK_EQUAL(SubmitErrorString(res.error()), "No active workers");116std::vector<std::function<void()>> tasks;117const auto range_res{threadPool.Submit(std::move(tasks))};118BOOST_CHECK(!range_res);119BOOST_CHECK_EQUAL(SubmitErrorString(range_res.error()), "No active workers");120}122// Test 1, submit tasks and verify completion123BOOST_AUTO_TEST_CASE(submit_tasks_complete_successfully)124{125int num_tasks = 50;127ThreadPool threadPool(POOL_NAME);128threadPool.Start(NUM_WORKERS_DEFAULT);129std::atomic<int> counter = 0;131// Store futures to ensure completion before checking counter.132std::vector<std::future<void>> futures;133futures.reserve(num_tasks);134for (int i = 1; i <= num_tasks; i++) {135futures.emplace_back(Submit(threadPool, [&counter, i]() {136counter.fetch_add(i, std::memory_order_relaxed);137}));138}140// Wait for all tasks to finish141WAIT_FOR(futures);142int expected_value = (num_tasks * (num_tasks + 1)) / 2; // Gauss sum.143BOOST_CHECK_EQUAL(counter.load(), expected_value);144BOOST_CHECK_EQUAL(threadPool.WorkQueueSize(), 0);145}147// Test 2, maintain all threads busy except one148BOOST_AUTO_TEST_CASE(single_available_worker_executes_all_tasks)149{150ThreadPool threadPool(POOL_NAME);151threadPool.Start(NUM_WORKERS_DEFAULT);152std::counting_semaphore<> blocker(0);153const auto blocking_tasks = BlockWorkers(threadPool, blocker, NUM_WORKERS_DEFAULT - 1);155// Now execute tasks on the single available worker156// and check that all the tasks are executed.157int num_tasks = 15;158int counter = 0;160// Store futures to wait on161std::vector<std::future<void>> futures(num_tasks);162for (auto& f : futures) f = Submit(threadPool, [&counter]{ counter++; });164WAIT_FOR(futures);165BOOST_CHECK_EQUAL(counter, num_tasks);167blocker.release(NUM_WORKERS_DEFAULT - 1);168WAIT_FOR(blocking_tasks);169threadPool.Stop();170BOOST_CHECK_EQUAL(threadPool.WorkersCount(), 0);171}173// Test 3, wait for work to finish174BOOST_AUTO_TEST_CASE(wait_for_task_to_finish)175{176ThreadPool threadPool(POOL_NAME);177threadPool.Start(NUM_WORKERS_DEFAULT);178std::atomic<bool> flag = false;179std::future<void> future = Submit(threadPool, [&flag]() {180UninterruptibleSleep(200ms);181flag.store(true, std::memory_order_release);182});183BOOST_CHECK(future.wait_for(TEST_WAIT_TIMEOUT) == std::future_status::ready);184BOOST_CHECK(flag.load(std::memory_order_acquire));185}187// Test 4, obtain result object188BOOST_AUTO_TEST_CASE(get_result_from_completed_task)189{190ThreadPool threadPool(POOL_NAME);191threadPool.Start(NUM_WORKERS_DEFAULT);192std::future<bool> future_bool = Submit(threadPool, []() { return true; });193BOOST_CHECK(future_bool.get());195std::future<std::string> future_str = Submit(threadPool, []() { return std::string("true"); });196std::string result = future_str.get();197BOOST_CHECK_EQUAL(result, "true");198}200// Test 5, throw exception and catch it on the consumer side201BOOST_AUTO_TEST_CASE(task_exception_propagates_to_future)202{203ThreadPool threadPool(POOL_NAME);204threadPool.Start(NUM_WORKERS_DEFAULT);206const auto make_err{[&](size_t n) { return strprintf("error on thread #%s", n); }};208const int num_tasks = 5;209std::vector<std::future<void>> futures;210futures.reserve(num_tasks);211for (int i = 0; i < num_tasks; i++) {212futures.emplace_back(Submit(threadPool, [&make_err, i] { throw std::runtime_error(make_err(i)); }));213}215for (int i = 0; i < num_tasks; i++) {216BOOST_CHECK_EXCEPTION(futures[i].get(), std::runtime_error, HasReason{make_err(i)});217}218}220// Test 6, all workers are busy, help them by processing tasks from outside221BOOST_AUTO_TEST_CASE(process_tasks_manually_when_workers_busy)222{223ThreadPool threadPool(POOL_NAME);224threadPool.Start(NUM_WORKERS_DEFAULT);226std::counting_semaphore<> blocker(0);227const auto& blocking_tasks = BlockWorkers(threadPool, blocker, NUM_WORKERS_DEFAULT);229// Now submit tasks and check that none of them are executed.230int num_tasks = 20;231std::atomic<int> counter = 0;232for (int i = 0; i < num_tasks; i++) {233(void)Submit(threadPool, [&counter]() {234counter.fetch_add(1, std::memory_order_relaxed);235});236}237UninterruptibleSleep(100ms);238BOOST_CHECK_EQUAL(threadPool.WorkQueueSize(), num_tasks);240// Now process manually241for (int i = 0; i < num_tasks; i++) {242threadPool.ProcessTask();243}244BOOST_CHECK_EQUAL(counter.load(), num_tasks);245BOOST_CHECK_EQUAL(threadPool.WorkQueueSize(), 0);246blocker.release(NUM_WORKERS_DEFAULT);247threadPool.Stop();248WAIT_FOR(blocking_tasks);249}
Independent explanations by MyBitcoinExplorer. Not affiliated with or endorsed by Bitcoin Core. Guides are educational and do not replace the source or its tests.
Bitcoin Core source © its contributors, distributed under the MIT license. Original notices and bundled third-party licenses are retained in the source tree.