-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththread_pool.hpp
87 lines (77 loc) · 1.66 KB
/
thread_pool.hpp
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
#ifndef THREAD_POOL_H
#define THREAD_POOL_H
#include "sync_queue.hpp"
#include <iostream>
#include <vector>
#include <list>
#include <functional>
#include <memory>
#include <atomic>
#include <thread>
class ThreadPool
{
public:
using Task = std::function<void()>;
ThreadPool(int threadNum = std::thread::hardware_concurrency(), int maxTaskNums = 64): m_queue(maxTaskNums)
{
m_running = true;
// 创建固定数量的线程
for (int i = 0; i < threadNum; i++)
{
m_threads.emplace_back(std::make_shared<std::thread> (
&ThreadPool::ThreadPoll,
this
));
}
}
~ThreadPool()
{
std::call_once(m_flag, [this]() {
Shutdown();
})
}
void AddTask(Task &&task)
{
m_queue.Add(std::forward<Task> (task));
}
void AddTask(const Task &task)
{
m_queue.Add(task);
}
private:
void ThreadPoll()
{
while (m_running)
{
std::list<Task> list;
m_queue.BatchGet(list);
for (auto &task: list)
{
if (!m_running)
{
return;
}
task();
}
}
}
void Shutdown()
{
m_queue.Shutdown();
m_running = false;
for (auto thread : m_threads)
{
if (thread)
{
thread->join();
}
}
m_threads.clear();
}
private:
SyncQueue m_queue;
std::atomic_bool m_running;
std::once_flag m_flag;
std::vector<std::shared_ptr<std::thread>> m_threads;
}
#endif