-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathThreadPool.h
109 lines (93 loc) · 1.7 KB
/
ThreadPool.h
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
#ifndef _ASYNC_THREAD_POOL_H__
#define _ASYNC_THREAD_POOL_H__
#include <thread>
#include <mutex>
#include <vector>
#include <queue>
#include <future>
#include <functional>
struct Task
{
std::function<void()> task;
std::function<void()> callback;
};
class ThreadTask
{
public:
ThreadTask() {}
~ThreadTask()
{
this->_condition.notify_all();
this->_thread.join();
}
void init()
{
_thread = std::thread(
[this]()
{
while (true)
{
std::unique_lock<std::mutex> lock(this->_queueMutex);
this->_condition.wait(lock,
[this] { return !this->_taskQueue.empty(); });
auto task = this->_taskQueue.front();
this->_taskQueue.pop();
task.task();
if (task.callback != nullptr)
task.callback();
}
}
);
}
void add(std::function<void()> func, std::function<void()> callback = nullptr)
{
Task task;
task.task = func;
task.callback = callback;
_taskQueue.push(task);
this->_condition.notify_one();
}
int getSize()
{
return _taskQueue.size();
}
private:
std::thread _thread;
std::queue<Task> _taskQueue;
std::mutex _queueMutex;
std::condition_variable _condition;
};
class ThreadPool
{
public:
ThreadPool() {}
~ThreadPool()
{
for (auto& t : _workers)
{
delete t;
}
}
void init(int size)
{
for (int i = 0; i < size; ++i)
{
ThreadTask *task = new ThreadTask;
task->init();
_workers.emplace_back(task);
}
}
void add(std::function<void()> task, std::function<void()> callback = nullptr)
{
int index = 0;
for (int i = 1; i < _workers.size(); ++i)
{
if (_workers[i]->getSize() < _workers[index]->getSize())
index = i;
}
_workers[index]->add(task, callback);
}
private:
std::vector<ThreadTask*> _workers;
};
#endif