-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_thread_pool.cpp
More file actions
355 lines (278 loc) · 9.73 KB
/
Copy pathtest_thread_pool.cpp
File metadata and controls
355 lines (278 loc) · 9.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
/**
* @file test_thread_pool.cpp
* @brief Unit tests for ThreadPool
*/
#include <gtest/gtest.h>
#include <spdlog/sinks/ringbuffer_sink.h>
#include <spdlog/spdlog.h>
#include <algorithm>
#include <atomic>
#include <chrono>
#include <stdexcept>
#include <string>
#include <thread>
#include <vector>
#include "concurrency/logger.hpp"
#include "concurrency/task.hpp"
#include "concurrency/thread_pool.hpp"
using namespace keystone::concurrency;
// Test: Create and destroy ThreadPool
// Under sanitizer builds (asan/tsan/ubsan/lsan), thread startup/join
// instrumentation makes ThreadPool(4) + ~ThreadPool() exceed CTest's timeout,
// so the test skips itself at runtime when compiled with
// -DKEYSTONE_SANITIZER_BUILD=1 (injected by the Makefile %.asan/%.ubsan/%.lsan/%.tsan
// rules and by the asan/ubsan/tsan CMake presets). The non-sanitizer
// `unit-tests` CI job runs it normally. See issues #511 and #586.
TEST(ThreadPoolTest, CreateAndDestroy) {
#ifdef KEYSTONE_SANITIZER_BUILD
GTEST_SKIP() << "Disabled under sanitizers (#586): construction+destruction "
"exceeds CTest timeout under thread instrumentation.";
#endif
ThreadPool pool(4);
EXPECT_EQ(pool.size(), 4u);
}
// Test: Submit and execute function
TEST(ThreadPoolTest, SubmitFunction) {
ThreadPool pool(2);
std::atomic<int32_t> counter{0};
pool.submit([&]() { counter.fetch_add(1); });
// Wait for execution
std::this_thread::sleep_for(std::chrono::milliseconds(100));
EXPECT_EQ(counter.load(), 1);
}
// Test: Submit multiple functions
TEST(ThreadPoolTest, SubmitMultipleFunctions) {
ThreadPool pool(4);
std::atomic<int32_t> counter{0};
for (int32_t i = 0; i < 10; ++i) {
pool.submit([&]() { counter.fetch_add(1); });
}
// Wait for all to complete
std::this_thread::sleep_for(std::chrono::milliseconds(200));
EXPECT_EQ(counter.load(), 10);
}
// Test: Submit coroutine handle
TEST(ThreadPoolTest, SubmitCoroutineHandle) {
ThreadPool pool(2);
std::atomic<bool> executed{false};
// Create a simple coroutine lambda that returns Task<void>
auto createTask = [&]() -> Task<void> {
executed.store(true);
co_return;
};
// Create task on heap to prevent dangling pointer
auto task = std::make_shared<Task<void>>(createTask());
// Submit task for execution by manually resuming
// Capture shared_ptr to keep task alive
pool.submit([task]() { task->resume(); });
std::this_thread::sleep_for(std::chrono::milliseconds(100));
EXPECT_TRUE(executed.load());
}
// Test: Parallel execution
TEST(ThreadPoolTest, ParallelExecution) {
ThreadPool pool(4);
std::atomic<int32_t> counter{0};
std::atomic<int32_t> max_concurrent{0};
std::atomic<int32_t> current_concurrent{0};
auto work = [&]() {
int32_t concurrent = current_concurrent.fetch_add(1) + 1;
// Update max if this is higher
int32_t expected_max = max_concurrent.load();
while (concurrent > expected_max) {
if (max_concurrent.compare_exchange_weak(expected_max, concurrent)) {
break;
}
}
// Simulate work
std::this_thread::sleep_for(std::chrono::milliseconds(10));
current_concurrent.fetch_sub(1);
counter.fetch_add(1);
};
// Submit 8 tasks
for (int32_t i = 0; i < 8; ++i) {
pool.submit(work);
}
// Wait for completion
std::this_thread::sleep_for(std::chrono::milliseconds(300));
EXPECT_EQ(counter.load(), 8);
// With 4 threads, we should see some parallelism
EXPECT_GT(max_concurrent.load(), 1);
}
// Test: Graceful shutdown
TEST(ThreadPoolTest, GracefulShutdown) {
ThreadPool pool(2);
std::atomic<int32_t> counter{0};
// Submit some work
for (int32_t i = 0; i < 5; ++i) {
pool.submit([&]() {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
counter.fetch_add(1);
});
}
// Shutdown should wait for all work to complete
pool.shutdown();
EXPECT_EQ(counter.load(), 5);
EXPECT_TRUE(pool.is_shutting_down());
}
// Test: No new work accepted after shutdown
TEST(ThreadPoolTest, NoWorkAfterShutdown) {
ThreadPool pool(2);
std::atomic<int32_t> counter{0};
pool.shutdown();
// Try to submit work after shutdown
pool.submit([&]() { counter.fetch_add(1); });
std::this_thread::sleep_for(std::chrono::milliseconds(100));
// Work should not be executed
EXPECT_EQ(counter.load(), 0);
}
// Test: Thread pool with hardware_concurrency threads
// Same sanitizer-skip rationale as ThreadPoolTest.CreateAndDestroy above.
// See issues #511 and #586.
TEST(ThreadPoolTest, HardwareConcurrency) {
#ifdef KEYSTONE_SANITIZER_BUILD
GTEST_SKIP() << "Disabled under sanitizers (#586): construction+destruction "
"exceeds CTest timeout under thread instrumentation.";
#endif
ThreadPool pool; // Uses std::thread::hardware_concurrency()
EXPECT_GT(pool.size(), 0);
EXPECT_LE(pool.size(), std::thread::hardware_concurrency());
}
// Test: Exception handling in worker
TEST(ThreadPoolTest, ExceptionHandling) {
ThreadPool pool(2);
std::atomic<int32_t> counter{0};
// Submit task that throws
pool.submit([]() { throw std::runtime_error("Test exception"); });
// Submit normal task
pool.submit([&]() { counter.fetch_add(1); });
std::this_thread::sleep_for(std::chrono::milliseconds(100));
// Normal task should still execute despite exception in other task
EXPECT_EQ(counter.load(), 1);
}
// Test: Thread safety with concurrent submissions
TEST(ThreadPoolTest, ConcurrentSubmissions) {
ThreadPool pool(4);
std::atomic<int32_t> counter{0};
// Launch multiple threads that submit work
std::vector<std::thread> submitters;
for (int32_t i = 0; i < 4; ++i) {
submitters.emplace_back([&]() {
for (int32_t j = 0; j < 25; ++j) {
pool.submit([&]() { counter.fetch_add(1); });
}
});
}
// Wait for all submitters to finish
for (auto& t : submitters) {
t.join();
}
// Wait for all work to complete
std::this_thread::sleep_for(std::chrono::milliseconds(500));
EXPECT_EQ(counter.load(), 100);
}
// Test: GracefulShutdown drains queue by design, not incidentally.
// Submits bursts of work and then calls shutdown() immediately; all submitted
// work must be counted even though shutdown() races with the workers.
TEST(ThreadPoolTest, GracefulShutdownDrainsQueueExplicitly) {
ThreadPool pool(4);
std::atomic<int> counter{0};
// Submit a burst of short-lived tasks before calling shutdown().
for (int32_t i = 0; i < 20; ++i) {
pool.submit([&]() { counter.fetch_add(1); });
}
// shutdown() must not return until every submitted task has executed.
pool.shutdown();
EXPECT_EQ(counter.load(), 20);
EXPECT_TRUE(pool.is_shutting_down());
}
// Test: Destructor calls shutdown
TEST(ThreadPoolTest, DestructorShutdown) {
std::atomic<int32_t> counter{0};
{
ThreadPool pool(2);
for (int32_t i = 0; i < 5; ++i) {
pool.submit([&]() {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
counter.fetch_add(1);
});
}
// Pool destroyed here, should wait for work
}
// After scope, all work should be done
EXPECT_EQ(counter.load(), 5);
}
// ---------------------------------------------------------------------------
// Logger output assertions for worker exception events
// ---------------------------------------------------------------------------
namespace {
/// Capture all spdlog "keystone" lines produced while @p fn runs.
std::vector<std::string> captureThreadPoolLogLines(std::function<void()> fn) {
Logger::init(spdlog::level::trace);
auto logger = spdlog::get("keystone");
auto sink = std::make_shared<spdlog::sinks::ringbuffer_sink_mt>(256);
sink->set_level(spdlog::level::trace);
logger->sinks().push_back(sink);
fn();
logger->flush();
auto& sinks = logger->sinks();
sinks.erase(std::remove(sinks.begin(), sinks.end(), sink), sinks.end());
return sink->last_formatted();
}
bool anyLineContains(const std::vector<std::string>& lines,
const std::string& substr) {
for (const auto& line : lines) {
if (line.find(substr) != std::string::npos) {
return true;
}
}
return false;
}
} // namespace
// Test: std::exception thrown in worker is logged at error level
TEST(ThreadPoolLogTest, WorkerStdExceptionIsLogged) {
Logger::shutdown();
std::vector<std::string> lines;
{
ThreadPool pool(1);
lines = captureThreadPoolLogLines([&]() {
std::atomic<bool> done{false};
pool.submit([&done]() {
done.store(true);
throw std::runtime_error("worker-boom");
});
// Wait for the task to execute and the exception to be caught/logged
for (int i = 0; i < 50 && !done.load(); ++i) {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
// Give the catch block a moment to emit the log line
std::this_thread::sleep_for(std::chrono::milliseconds(50));
});
}
EXPECT_TRUE(anyLineContains(lines, "worker-boom"))
<< "Expected exception message in log output";
EXPECT_TRUE(anyLineContains(lines, "Exception in worker"))
<< "Expected 'Exception in worker' prefix in log output";
Logger::shutdown();
}
// Test: unknown exception thrown in worker is logged at error level
TEST(ThreadPoolLogTest, WorkerUnknownExceptionIsLogged) {
Logger::shutdown();
std::vector<std::string> lines;
{
ThreadPool pool(1);
lines = captureThreadPoolLogLines([&]() {
std::atomic<bool> done{false};
pool.submit([&done]() {
done.store(true);
throw 42; // non-std::exception
});
for (int i = 0; i < 50 && !done.load(); ++i) {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
std::this_thread::sleep_for(std::chrono::milliseconds(50));
});
}
EXPECT_TRUE(anyLineContains(lines, "Unknown exception"))
<< "Expected 'Unknown exception' in log output for non-std throw";
Logger::shutdown();
}