-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathasync_executor.cpp
More file actions
388 lines (327 loc) · 12.4 KB
/
async_executor.cpp
File metadata and controls
388 lines (327 loc) · 12.4 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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
#include "async_executor.hpp"
#include <spdlog/spdlog.h>
#include <thread>
namespace atom::async {
// 构造函数
AsyncExecutor::AsyncExecutor(Configuration config)
: m_config(std::move(config)),
// C++20 信号量初始化 - 初始值为0
m_taskSemaphore(0) {
// 确保线程数的合理性
if (m_config.minThreads < 1)
m_config.minThreads = 1;
if (m_config.maxThreads < m_config.minThreads)
m_config.maxThreads = m_config.minThreads;
// 为每个线程预先创建任务窃取队列
if (m_config.useWorkStealing) {
m_perThreadQueues.reserve(m_config.maxThreads);
for (size_t i = 0; i < m_config.maxThreads; ++i) {
m_perThreadQueues.emplace_back(
std::make_unique<WorkStealingQueue>());
}
}
}
// 移动构造函数
AsyncExecutor::AsyncExecutor(AsyncExecutor&& other) noexcept
: m_config(std::move(other.m_config)),
m_isRunning(other.m_isRunning.load(std::memory_order_acquire)),
m_activeThreads(other.m_activeThreads.load(std::memory_order_relaxed)),
m_pendingTasks(other.m_pendingTasks.load(std::memory_order_relaxed)),
m_completedTasks(other.m_completedTasks.load(std::memory_order_relaxed)),
// C++20 信号量不可复制,但可以移动
m_taskSemaphore(0) {
std::scoped_lock lock(m_queueMutex, other.m_queueMutex);
m_taskQueue = std::move(other.m_taskQueue);
m_perThreadQueues = std::move(other.m_perThreadQueues);
other.stop();
if (m_isRunning) {
start();
}
}
// 移动赋值操作符
AsyncExecutor& AsyncExecutor::operator=(AsyncExecutor&& other) noexcept {
if (this != &other) {
stop();
m_config = std::move(other.m_config);
m_isRunning.store(other.m_isRunning.load(std::memory_order_acquire),
std::memory_order_release);
m_activeThreads.store(
other.m_activeThreads.load(std::memory_order_relaxed),
std::memory_order_relaxed);
m_pendingTasks.store(
other.m_pendingTasks.load(std::memory_order_relaxed),
std::memory_order_relaxed);
m_completedTasks.store(
other.m_completedTasks.load(std::memory_order_relaxed),
std::memory_order_relaxed);
std::scoped_lock lock(m_queueMutex, other.m_queueMutex);
m_taskQueue = std::move(other.m_taskQueue);
m_perThreadQueues = std::move(other.m_perThreadQueues);
other.stop();
if (m_isRunning) {
start();
}
}
return *this;
}
// 析构函数
AsyncExecutor::~AsyncExecutor() { stop(); }
// 启动线程池
void AsyncExecutor::start() {
if (m_isRunning.exchange(true, std::memory_order_acq_rel)) {
return; // 已经在运行
}
try {
// 保存每个线程的 native_handle
m_threadHandles.clear();
m_threadHandles.reserve(m_config.minThreads);
for (size_t i = 0; i < m_config.minThreads; ++i) {
m_threads.emplace_back([this, id = i](std::stop_token stoken) {
workerLoop(id, stoken);
});
m_threadHandles.push_back(m_threads.back().native_handle());
}
// 设置线程优先级
if (m_config.setPriority) {
for (auto handle : m_threadHandles) {
setThreadPriority(handle);
}
}
// 启动统计信息收集线程
if (m_config.statInterval.count() > 0) {
m_statsThread = std::jthread(
[this](std::stop_token stoken) { statsLoop(stoken); });
}
spdlog::info("AsyncExecutor started with {} threads",
m_config.minThreads);
} catch (const std::exception& e) {
stop();
spdlog::error("Failed to start AsyncExecutor: {}", e.what());
throw;
}
}
// 停止线程池
void AsyncExecutor::stop() {
if (!m_isRunning.exchange(false, std::memory_order_acq_rel)) {
return; // 已经停止
}
// 使用 C++20 特性 - jthread 自动停止
m_threads.clear();
if (m_statsThread.joinable()) {
m_statsThread = {};
}
{
std::lock_guard lock(m_queueMutex);
while (!m_taskQueue.empty()) {
m_taskQueue.pop();
}
}
// 重置计数器
m_pendingTasks.store(0, std::memory_order_relaxed);
m_activeThreads.store(0, std::memory_order_relaxed);
spdlog::info("AsyncExecutor stopped");
}
// 将任务添加到队列
void AsyncExecutor::enqueueTask(std::function<void()> task, int priority) {
if (!task) {
throw ExecutorException("Cannot enqueue empty task");
}
// 增加待处理任务计数
m_pendingTasks.fetch_add(1, std::memory_order_relaxed);
// 如果启用了工作窃取,尝试分配给最不忙的线程队列
if (m_config.useWorkStealing && !m_perThreadQueues.empty()) {
// 找到最短的队列用于负载均衡
size_t minQueueIndex = 0;
size_t minQueueSize = SIZE_MAX;
for (size_t i = 0; i < m_perThreadQueues.size(); ++i) {
auto& queue = *m_perThreadQueues[i];
std::lock_guard queueLock(queue.mutex);
if (queue.tasks.size() < minQueueSize) {
minQueueSize = queue.tasks.size();
minQueueIndex = i;
// 如果找到空队列,立即使用
if (minQueueSize == 0) {
break;
}
}
}
// 添加任务到选择的队列
auto& targetQueue = *m_perThreadQueues[minQueueIndex];
{
std::lock_guard queueLock(targetQueue.mutex);
targetQueue.tasks.push_back({std::move(task), priority});
}
} else {
// 使用全局队列
{
std::lock_guard lock(m_queueMutex);
m_taskQueue.push({std::move(task), priority});
}
}
// 增加信号量计数,并通知等待的线程
m_taskSemaphore.release();
m_condition.notify_one();
}
// 线程工作循环
void AsyncExecutor::workerLoop(size_t threadId, std::stop_token stoken) {
try {
// 设置线程亲和性(如果配置启用)
if (m_config.pinThreads) {
setThreadAffinity(threadId);
}
while (!stoken.stop_requested()) {
// 尝试获取任务
auto task = dequeueTask(threadId);
// 如果没有任务,尝试从其他线程窃取
if (!task && m_config.useWorkStealing) {
task = stealTask(threadId);
}
// 如果有任务,执行它
if (task) {
try {
task->func();
} catch (const std::exception& e) {
spdlog::error("Task execution failed: {}", e.what());
} catch (...) {
spdlog::error(
"Task execution failed with unknown exception");
}
m_pendingTasks.fetch_sub(1, std::memory_order_relaxed);
} else {
// 没有任务,等待信号量或停止信号
if (!m_taskSemaphore.try_acquire_for(
m_config.threadIdleTimeout)) {
// 超时,如果当前线程数大于最小线程数,可以退出
if (m_threads.size() > m_config.minThreads) {
break; // 线程将终止
}
}
}
}
} catch (const std::exception& e) {
spdlog::error("Thread {} encountered an exception: {}", threadId,
e.what());
} catch (...) {
spdlog::error("Thread {} encountered an unknown exception", threadId);
}
}
// 从队列获取任务
std::optional<AsyncExecutor::TaskItem> AsyncExecutor::dequeueTask(
size_t threadId) {
// 先检查线程特定队列(如果启用了工作窃取)
if (m_config.useWorkStealing && threadId < m_perThreadQueues.size()) {
auto& queue = *m_perThreadQueues[threadId];
std::lock_guard queueLock(queue.mutex);
if (!queue.tasks.empty()) {
auto task = std::move(queue.tasks.front());
queue.tasks.pop_front();
return task;
}
}
// 否则从主队列获取
std::unique_lock lock(m_queueMutex);
if (!m_taskQueue.empty()) {
auto task = m_taskQueue.top();
m_taskQueue.pop();
return task;
}
return std::nullopt;
}
// 尝试从其他线程窃取任务
std::optional<AsyncExecutor::TaskItem> AsyncExecutor::stealTask(
size_t currentId) {
if (!m_config.useWorkStealing || m_perThreadQueues.empty()) {
return std::nullopt;
}
// 从其他线程的队列尾部窃取任务(以减少竞争)
size_t queueCount = m_perThreadQueues.size();
size_t startIndex = (currentId + 1) % queueCount; // 从下一个线程开始
for (size_t i = 0; i < queueCount - 1; ++i) {
size_t index = (startIndex + i) % queueCount;
auto& queue = *m_perThreadQueues[index];
std::lock_guard queueLock(queue.mutex);
if (!queue.tasks.empty()) {
// 从队列尾部窃取(通常是较大的工作单元)
auto task = std::move(queue.tasks.back());
queue.tasks.pop_back();
return task;
}
}
return std::nullopt;
}
// 设置线程亲和性
void AsyncExecutor::setThreadAffinity(size_t threadId) {
#if defined(ATOM_PLATFORM_WINDOWS)
// Windows平台实现
DWORD_PTR mask = (static_cast<DWORD_PTR>(1)
<< (threadId % std::thread::hardware_concurrency()));
SetThreadAffinityMask(GetCurrentThread(), mask);
#elif defined(ATOM_PLATFORM_LINUX)
// Linux平台实现
cpu_set_t cpuset;
CPU_ZERO(&cpuset);
CPU_SET(threadId % std::thread::hardware_concurrency(), &cpuset);
pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t), &cpuset);
#elif defined(ATOM_PLATFORM_MACOS)
// macOS平台实现更复杂,有特殊API
thread_affinity_policy_data_t policy = {
static_cast<integer_t>(threadId % std::thread::hardware_concurrency())};
thread_policy_set(pthread_mach_thread_np(pthread_self()),
THREAD_AFFINITY_POLICY, (thread_policy_t)&policy,
THREAD_AFFINITY_POLICY_COUNT);
#endif
}
// 设置线程优先级
void AsyncExecutor::setThreadPriority(std::thread::native_handle_type handle) {
#if defined(ATOM_PLATFORM_WINDOWS)
// Windows平台实现
int winPriority = THREAD_PRIORITY_NORMAL;
if (m_config.threadPriority > 0) {
winPriority = THREAD_PRIORITY_ABOVE_NORMAL;
} else if (m_config.threadPriority < 0) {
winPriority = THREAD_PRIORITY_BELOW_NORMAL;
}
::SetThreadPriority(reinterpret_cast<HANDLE>(handle), winPriority);
#elif defined(ATOM_PLATFORM_LINUX)
// Linux平台实现
int policy;
struct sched_param param;
pthread_getschedparam(handle, &policy, ¶m);
// 调整优先级
int min_prio = sched_get_priority_min(policy);
int max_prio = sched_get_priority_max(policy);
int prio_range = max_prio - min_prio;
// 映射自定义优先级到系统范围
param.sched_priority =
min_prio + ((prio_range * (m_config.threadPriority + 100)) / 200);
pthread_setschedparam(handle, policy, ¶m);
#elif defined(ATOM_PLATFORM_MACOS)
// macOS平台实现
struct sched_param param;
int policy;
pthread_getschedparam(handle, &policy, ¶m);
// 调整优先级
int min_prio = sched_get_priority_min(policy);
int max_prio = sched_get_priority_max(policy);
int prio_range = max_prio - min_prio;
// 映射自定义优先级到系统范围
param.sched_priority =
min_prio + ((prio_range * (m_config.threadPriority + 100)) / 200);
pthread_setschedparam(handle, policy, ¶m);
#endif
}
// 统计信息收集线程
void AsyncExecutor::statsLoop(std::stop_token stoken) {
while (!stoken.stop_requested()) {
// 统计信息收集在此实现
size_t active = m_activeThreads.load(std::memory_order_relaxed);
size_t pending = m_pendingTasks.load(std::memory_order_relaxed);
size_t completed = m_completedTasks.load(std::memory_order_relaxed);
spdlog::debug(
"AsyncExecutor stats - Active: {}, Pending: {}, Completed: {}",
active, pending, completed);
// 使用C++20的新特性 jthread 和 stop_token 的条件等待
std::this_thread::sleep_for(m_config.statInterval);
}
}
} // namespace atom::async