-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreadPool.h
More file actions
132 lines (106 loc) · 3.58 KB
/
ThreadPool.h
File metadata and controls
132 lines (106 loc) · 3.58 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
#ifndef __THREAD_POOL_H__
#define __THREAD_POOL_H__
#include <atomic>
#include <thread>
#include <iostream>
#include <vector>
#include <functional>
#include <queue>
#include <mutex>
#include <condition_variable>
#include <future>
class ThreadPool {
public:
explicit ThreadPool(size_t threadNum) : stop(false) {
for (int i = 0; i < threadNum; i ++) {
workers.emplace_back([this]() {
while(1) {
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(queue_mutex);
condition.wait(lock, [this]() {
return this->stop || !this->tasks.empty();
});
// 如果线程池已停止且任务队列为空,则线程退出
if (this->stop && this->tasks.empty()) {
return;
}
// 从队列中取出一个任务
task = std::move(this->tasks.front());
this->tasks.pop();
}
// 执行任务(注意:在锁外执行,避免长时间持有锁)
task();
}
});
}
}
template<class F, class... Args>
auto submit(F&& f, Args&&... args)
-> std::future<typename std::result_of<F(Args...)>::type> {
// 推导任务的返回类型
using result_type = typename std::result_of<F(Args...)>::type;
// 将任务和参数打包成一个无参数的可调用对象
// 使用std::packaged_task来获取异步结果
auto task = std::make_shared<std::packaged_task<result_type()>> (
std::bind(std::forward<F>(f), std::forward<Args>(args)...)
);
std::future<result_type> res = task->get_future();
{
std::lock_guard<std::mutex> lock(queue_mutex);
// 如果线程池已停止,不允许提交新任务
if (stop) {
throw std::runtime_error("submit on stopped ThreadPool");
}
// 将任务加入队列
tasks.emplace([task](){ (*task)(); });
}
// 通知一个等待的工作线程
condition.notify_one();
return res;
}
// 优雅关闭:等待所有已提交的任务完成
void shutdown() {
stop = true;
condition.notify_all();
// 等待所有工作线程结束
for(std::thread &worker : workers)
worker.join();
workers.clear();
}
// 立即关闭:不等待队列中剩余的任务
void shutdown_now() {
{
std::unique_lock<std::mutex> lock(queue_mutex);
stop = true;
// 清空任务队列
while(!tasks.empty()) tasks.pop();
}
condition.notify_all();
for(std::thread &worker : workers)
worker.join();
workers.clear();
}
// 获取等待执行的任务数量
size_t pending_tasks() const {
std::unique_lock<std::mutex> lock(queue_mutex);
return tasks.size();
}
// 析构函数自动关闭线程池
~ThreadPool() {
if(!stop) {
shutdown();
}
}
private:
// 工作线程组
std::vector<std::thread> workers;
// 任务队列
std::queue<std::function<void()>> tasks;
// 同步原语
mutable std::mutex queue_mutex;
std::condition_variable condition;
// 停止标志
std::atomic<bool> stop;
};
#endif