Bitcoin Core 30.99.0
P2P Digital Currency
threadpool_tests.cpp
Go to the documentation of this file.
1// Copyright (c) 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#include <common/system.h>
6#include <logging.h>
7#include <random.h>
8#include <util/string.h>
9#include <util/threadpool.h>
10#include <util/time.h>
11
12#include <boost/test/unit_test.hpp>
13
14// General test values
16constexpr char POOL_NAME[] = "test";
17constexpr auto WAIT_TIMEOUT = 120s;
18
22 LogInfo("thread pool workers count: %d", NUM_WORKERS_DEFAULT);
23 }
24};
25
26// Test Cases Overview
27// 0) Submit task to a non-started pool.
28// 1) Submit tasks and verify completion.
29// 2) Maintain all threads busy except one.
30// 3) Wait for work to finish.
31// 4) Wait for result object.
32// 5) The task throws an exception, catch must be done in the consumer side.
33// 6) Busy workers, help them by processing tasks externally.
34// 7) Recursive submission of tasks.
35// 8) Submit task when all threads are busy, stop pool and verify task gets executed.
36// 9) Congestion test; create more workers than available cores.
37// 10) Ensure Interrupt() prevents further submissions.
39
40#define WAIT_FOR(futures) \
41 do { \
42 for (const auto& f : futures) { \
43 BOOST_REQUIRE(f.wait_for(WAIT_TIMEOUT) == std::future_status::ready); \
44 } \
45 } while (0)
46
47// Block a number of worker threads by submitting tasks that wait on `blocker_future`.
48// Returns the futures of the blocking tasks, ensuring all have started and are waiting.
49std::vector<std::future<void>> BlockWorkers(ThreadPool& threadPool, const std::shared_future<void>& blocker_future, int num_of_threads_to_block)
50{
51 // Per-thread ready promises to ensure all workers are actually blocked
52 std::vector<std::promise<void>> ready_promises(num_of_threads_to_block);
53 std::vector<std::future<void>> ready_futures;
54 ready_futures.reserve(num_of_threads_to_block);
55 for (auto& p : ready_promises) ready_futures.emplace_back(p.get_future());
56
57 // Fill all workers with blocking tasks
58 std::vector<std::future<void>> blocking_tasks;
59 for (int i = 0; i < num_of_threads_to_block; i++) {
60 std::promise<void>& ready = ready_promises[i];
61 blocking_tasks.emplace_back(threadPool.Submit([blocker_future, &ready]() {
62 ready.set_value();
63 blocker_future.wait();
64 }));
65 }
66
67 // Wait until all threads are actually blocked
68 WAIT_FOR(ready_futures);
69 return blocking_tasks;
70}
71
72// Test 0, submit task to a non-started pool
73BOOST_AUTO_TEST_CASE(submit_task_before_start_fails)
74{
75 ThreadPool threadPool(POOL_NAME);
76 BOOST_CHECK_EXCEPTION((void)threadPool.Submit([]{ return false; }), std::runtime_error, [&](const std::runtime_error& e) {
77 BOOST_CHECK_EQUAL(e.what(), "No active workers; cannot accept new tasks");
78 return true;
79 });
80}
81
82// Test 1, submit tasks and verify completion
83BOOST_AUTO_TEST_CASE(submit_tasks_complete_successfully)
84{
85 int num_tasks = 50;
86
87 ThreadPool threadPool(POOL_NAME);
88 threadPool.Start(NUM_WORKERS_DEFAULT);
89 std::atomic<int> counter = 0;
90
91 // Store futures to ensure completion before checking counter.
92 std::vector<std::future<void>> futures;
93 futures.reserve(num_tasks);
94 for (int i = 1; i <= num_tasks; i++) {
95 futures.emplace_back(threadPool.Submit([&counter, i]() {
96 counter.fetch_add(i, std::memory_order_relaxed);
97 }));
98 }
99
100 // Wait for all tasks to finish
101 WAIT_FOR(futures);
102 int expected_value = (num_tasks * (num_tasks + 1)) / 2; // Gauss sum.
103 BOOST_CHECK_EQUAL(counter.load(), expected_value);
104 BOOST_CHECK_EQUAL(threadPool.WorkQueueSize(), 0);
105}
106
107// Test 2, maintain all threads busy except one
108BOOST_AUTO_TEST_CASE(single_available_worker_executes_all_tasks)
109{
110 ThreadPool threadPool(POOL_NAME);
111 threadPool.Start(NUM_WORKERS_DEFAULT);
112 // Single blocking future for all threads
113 std::promise<void> blocker;
114 std::shared_future<void> blocker_future(blocker.get_future());
115 const auto blocking_tasks = BlockWorkers(threadPool, blocker_future, NUM_WORKERS_DEFAULT - 1);
116
117 // Now execute tasks on the single available worker
118 // and check that all the tasks are executed.
119 int num_tasks = 15;
120 int counter = 0;
121
122 // Store futures to wait on
123 std::vector<std::future<void>> futures(num_tasks);
124 for (auto& f : futures) f = threadPool.Submit([&counter]{ counter++; });
125
126 WAIT_FOR(futures);
127 BOOST_CHECK_EQUAL(counter, num_tasks);
128
129 blocker.set_value();
130 WAIT_FOR(blocking_tasks);
131 threadPool.Stop();
132 BOOST_CHECK_EQUAL(threadPool.WorkersCount(), 0);
133}
134
135// Test 3, wait for work to finish
136BOOST_AUTO_TEST_CASE(wait_for_task_to_finish)
137{
138 ThreadPool threadPool(POOL_NAME);
139 threadPool.Start(NUM_WORKERS_DEFAULT);
140 std::atomic<bool> flag = false;
141 std::future<void> future = threadPool.Submit([&flag]() {
143 flag.store(true, std::memory_order_release);
144 });
145 BOOST_CHECK(future.wait_for(WAIT_TIMEOUT) == std::future_status::ready);
146 BOOST_CHECK(flag.load(std::memory_order_acquire));
147}
148
149// Test 4, obtain result object
150BOOST_AUTO_TEST_CASE(get_result_from_completed_task)
151{
152 ThreadPool threadPool(POOL_NAME);
153 threadPool.Start(NUM_WORKERS_DEFAULT);
154 std::future<bool> future_bool = threadPool.Submit([]() { return true; });
155 BOOST_CHECK(future_bool.get());
156
157 std::future<std::string> future_str = threadPool.Submit([]() { return std::string("true"); });
158 std::string result = future_str.get();
159 BOOST_CHECK_EQUAL(result, "true");
160}
161
162// Test 5, throw exception and catch it on the consumer side
163BOOST_AUTO_TEST_CASE(task_exception_propagates_to_future)
164{
165 ThreadPool threadPool(POOL_NAME);
166 threadPool.Start(NUM_WORKERS_DEFAULT);
167
168 int num_tasks = 5;
169 std::string err_msg{"something wrong happened"};
170 std::vector<std::future<void>> futures;
171 futures.reserve(num_tasks);
172 for (int i = 0; i < num_tasks; i++) {
173 futures.emplace_back(threadPool.Submit([err_msg, i]() {
174 throw std::runtime_error(err_msg + util::ToString(i));
175 }));
176 }
177
178 for (int i = 0; i < num_tasks; i++) {
179 BOOST_CHECK_EXCEPTION(futures.at(i).get(), std::runtime_error, [&](const std::runtime_error& e) {
180 BOOST_CHECK_EQUAL(e.what(), err_msg + util::ToString(i));
181 return true;
182 });
183 }
184}
185
186// Test 6, all workers are busy, help them by processing tasks from outside
187BOOST_AUTO_TEST_CASE(process_tasks_manually_when_workers_busy)
188{
189 ThreadPool threadPool(POOL_NAME);
190 threadPool.Start(NUM_WORKERS_DEFAULT);
191
192 std::promise<void> blocker;
193 std::shared_future<void> blocker_future(blocker.get_future());
194 const auto& blocking_tasks = BlockWorkers(threadPool, blocker_future, NUM_WORKERS_DEFAULT);
195
196 // Now submit tasks and check that none of them are executed.
197 int num_tasks = 20;
198 std::atomic<int> counter = 0;
199 for (int i = 0; i < num_tasks; i++) {
200 (void)threadPool.Submit([&counter]() {
201 counter.fetch_add(1, std::memory_order_relaxed);
202 });
203 }
205 BOOST_CHECK_EQUAL(threadPool.WorkQueueSize(), num_tasks);
206
207 // Now process manually
208 for (int i = 0; i < num_tasks; i++) {
209 threadPool.ProcessTask();
210 }
211 BOOST_CHECK_EQUAL(counter.load(), num_tasks);
212 BOOST_CHECK_EQUAL(threadPool.WorkQueueSize(), 0);
213 blocker.set_value();
214 threadPool.Stop();
215 WAIT_FOR(blocking_tasks);
216}
217
218// Test 7, submit tasks from other tasks
219BOOST_AUTO_TEST_CASE(recursive_task_submission)
220{
221 ThreadPool threadPool(POOL_NAME);
222 threadPool.Start(NUM_WORKERS_DEFAULT);
223
224 std::promise<void> signal;
225 (void)threadPool.Submit([&]() {
226 (void)threadPool.Submit([&]() {
227 signal.set_value();
228 });
229 });
230
231 signal.get_future().wait();
232 threadPool.Stop();
233}
234
235// Test 8, submit task when all threads are busy and then stop the pool
236BOOST_AUTO_TEST_CASE(task_submitted_while_busy_completes)
237{
238 ThreadPool threadPool(POOL_NAME);
239 threadPool.Start(NUM_WORKERS_DEFAULT);
240
241 std::promise<void> blocker;
242 std::shared_future<void> blocker_future(blocker.get_future());
243 const auto& blocking_tasks = BlockWorkers(threadPool, blocker_future, NUM_WORKERS_DEFAULT);
244
245 // Submit an extra task that should execute once a worker is free
246 std::future<bool> future = threadPool.Submit([]() { return true; });
247
248 // At this point, all workers are blocked, and the extra task is queued
249 BOOST_CHECK_EQUAL(threadPool.WorkQueueSize(), 1);
250
251 // Wait a short moment before unblocking the threads to mimic a concurrent shutdown
252 std::thread thread_unblocker([&blocker]() {
254 blocker.set_value();
255 });
256
257 // Stop the pool while the workers are still blocked
258 threadPool.Stop();
259
260 // Expect the submitted task to complete
261 BOOST_CHECK(future.get());
262 thread_unblocker.join();
263
264 // Obviously all the previously blocking tasks should be completed at this point too
265 WAIT_FOR(blocking_tasks);
266
267 // Pool should be stopped and no workers remaining
268 BOOST_CHECK_EQUAL(threadPool.WorkersCount(), 0);
269}
270
271// Test 9, more workers than available cores (congestion test)
272BOOST_AUTO_TEST_CASE(congestion_more_workers_than_cores)
273{
274 ThreadPool threadPool(POOL_NAME);
275 threadPool.Start(std::max(1, GetNumCores() * 2)); // Oversubscribe by 2×
276
277 int num_tasks = 200;
278 std::atomic<int> counter{0};
279
280 std::vector<std::future<void>> futures;
281 futures.reserve(num_tasks);
282 for (int i = 0; i < num_tasks; i++) {
283 futures.emplace_back(threadPool.Submit([&counter] {
284 counter.fetch_add(1, std::memory_order_relaxed);
285 }));
286 }
287
288 WAIT_FOR(futures);
289 BOOST_CHECK_EQUAL(counter.load(), num_tasks);
290}
291
292// Test 10, Interrupt() prevents further submissions
293BOOST_AUTO_TEST_CASE(interrupt_blocks_new_submissions)
294{
295 // 1) Interrupt from main thread
296 ThreadPool threadPool(POOL_NAME);
297 threadPool.Start(NUM_WORKERS_DEFAULT);
298 threadPool.Interrupt();
299 BOOST_CHECK_EXCEPTION((void)threadPool.Submit([]{}), std::runtime_error, [&](const std::runtime_error& e) {
300 BOOST_CHECK_EQUAL(e.what(), "No active workers; cannot accept new tasks");
301 return true;
302 });
303
304 // Reset pool
305 threadPool.Stop();
306
307 // 2) Interrupt() from a worker thread
308 // One worker is blocked, another calls Interrupt(), and the remaining one waits for tasks.
309 threadPool.Start(/*num_workers=*/3);
310 std::atomic<int> counter{0};
311 std::promise<void> blocker;
312 const auto blocking_tasks = BlockWorkers(threadPool, blocker.get_future().share(), 1);
313 threadPool.Submit([&threadPool, &counter]{
314 threadPool.Interrupt();
315 counter.fetch_add(1, std::memory_order_relaxed);
316 }).get();
317 blocker.set_value(); // unblock worker
318
319 BOOST_CHECK_EQUAL(counter.load(), 1);
320 threadPool.Stop();
321 WAIT_FOR(blocking_tasks);
322 BOOST_CHECK_EQUAL(threadPool.WorkersCount(), 0);
323}
324
Fast randomness source.
Definition: random.h:386
I randrange(I range) noexcept
Generate a random integer in the range [0..range), with range > 0.
Definition: random.h:254
Fixed-size thread pool for running arbitrary tasks concurrently.
Definition: threadpool.h:46
void Start(int num_workers) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Start worker threads.
Definition: threadpool.h:103
void ProcessTask() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Execute a single queued task synchronously.
Definition: threadpool.h:174
size_t WorkersCount() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Definition: threadpool.h:205
void Stop() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Stop all worker threads and wait for them to exit.
Definition: threadpool.h:125
void Interrupt() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Stop accepting new tasks and begin asynchronous shutdown.
Definition: threadpool.h:194
size_t WorkQueueSize() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Definition: threadpool.h:200
int GetNumCores()
Return the number of cores available on the current system.
Definition: system.cpp:109
BOOST_FIXTURE_TEST_SUITE(cuckoocache_tests, BasicTestingSetup)
Test Suite for CuckooCache.
BOOST_AUTO_TEST_SUITE_END()
#define LogInfo(...)
Definition: log.h:95
#define BOOST_CHECK_EQUAL(v1, v2)
Definition: object.cpp:17
#define BOOST_CHECK(expr)
Definition: object.cpp:16
std::vector< std::future< void > > BlockWorkers(ThreadPool &threadPool, const std::shared_future< void > &blocker_future, int num_of_threads_to_block)
#define WAIT_FOR(futures)
constexpr auto WAIT_TIMEOUT
constexpr char POOL_NAME[]
BOOST_AUTO_TEST_CASE(submit_task_before_start_fails)
int NUM_WORKERS_DEFAULT
void UninterruptibleSleep(const std::chrono::microseconds &n)
Definition: time.cpp:24