-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththread_pool.hpp
More file actions
63 lines (57 loc) · 1.79 KB
/
thread_pool.hpp
File metadata and controls
63 lines (57 loc) · 1.79 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
#include <mutex>
#include <vector>
#include <thread>
#include <queue>
#include <condition_variable>
#include <functional>
#include <stdexcept>
typedef std::function<void()> Task;
class ThreadPool{
public:
explicit ThreadPool(size_t threads = std::thread::hardware_concurrency()):_stop(false){
for(int i = 0; i < threads; i++){
_works.emplace_back([this]{
while(true){
Task task;
{
std::unique_lock<std::mutex> lock(this->_mtx);
_cv.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();//执行任务
}
});
}
}
~ThreadPool(){
{
std::unique_lock<std::mutex> lock(_mtx);
_stop = true;
} // 锁释放
_cv.notify_all();
for(auto &work:_works){
work.join();
}
}
// 提交任务
template<class F, class... Args>
auto enqueue(F&& f, Args&&... args){
auto task = std::bind(std::forward<F>(f), std::forward<Args>(args)...);
{
std::unique_lock<std::mutex> lock(_mtx);
if(_stop) throw std::runtime_error("enqueue on stopped ThreadPool");
_tasks.emplace([task] {task();});
}
_cv.notify_one();// 唤醒一个线程
}
private:
std::mutex _mtx;
std::condition_variable _cv;
bool _stop;
std::vector<std::thread> _works; // 工作线程
std::queue<Task> _tasks; // 任务队列
};