/
ThreadPool.h
92 lines (76 loc) · 3.05 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
#pragma once
#include <deque>
#include <thread>
#include <memory>
#include <atomic>
#include <mutex>
#include <condition_variable>
#include <vector>
#include <functional>
#include <future>
class ThreadPool {
public:
void start(unsigned int numberOfThreads) {
for(unsigned int i{0}; i < numberOfThreads; i++) {
threads.push_back(std::thread(&ThreadPool::worker, this));
}
}
void worker() {
while (!done) {
std::function<void()> work;
{
std::unique_lock<std::mutex> ul(m);
cv.wait(ul,[&] { return ( hasWork() || done );});
work = pull();
}
if(done) break;
work();
}
}
void add(std::function<void()> work) {
{
std::lock_guard<std::mutex> guard(m);
workQueue.push_front(work);
}
cv.notify_one();
}
template<class F, class... Args>
auto submit(F&& task_function, Args&&... args)
{
using T = decltype(task_function(args...));
auto task = std::make_shared<std::packaged_task<T()>> (
std::bind(std::forward<F>(task_function), std::forward<Args>(args)...)
);
std::future<T> result = task->get_future();
auto work = [task] () { (*task)(); };
{
std::lock_guard<std::mutex> guard(m);
workQueue.push_front(work);
}
cv.notify_one();
return result;
}
bool hasWork() {
return !workQueue.empty();
}
std::function<void()> pull() {
if(workQueue.empty()) {
return []{};
}
auto work = workQueue.back();
workQueue.pop_back();
return work;
}
~ThreadPool() {
done = true;
cv.notify_all();
for(auto& t:threads) {
t.join();
}
}
std::vector<std::thread> threads;
std::deque<std::function<void()>> workQueue;
std::atomic<bool> done {false};
std::mutex m;
std::condition_variable cv;
};