-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathThreadPoolExecutor.hpp
72 lines (60 loc) · 1.32 KB
/
ThreadPoolExecutor.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
#pragma once
#include <condition_variable>
#include <mutex>
#include <queue>
#include <thread>
#include <vector>
#include "Executor.hpp"
namespace Pledge {
class ThreadPoolExecutor : public Executor
{
public:
inline void add(Func func) override
{
{
std::lock_guard<std::mutex> g(m_queueMutex);
m_queue.push(std::move(func));
}
m_queueCond.notify_one();
}
inline ThreadPoolExecutor(size_t threadCount = 8)
{
m_threads.reserve(threadCount);
for (size_t i = 0; i < threadCount; ++i)
m_threads.emplace_back(std::bind(&ThreadPoolExecutor::exec, this));
}
inline ~ThreadPoolExecutor()
{
{
std::unique_lock<std::mutex> lock(m_queueMutex);
m_running = false;
}
m_queueCond.notify_all();
for (std::thread& t : m_threads)
t.join();
}
private:
inline void exec()
{
for (;;) {
Func func;
{
std::unique_lock<std::mutex> lock(m_queueMutex);
while (m_running && m_queue.empty())
m_queueCond.wait(lock);
if (m_queue.empty())
break;
func = std::move(m_queue.front());
m_queue.pop();
}
func();
}
}
private:
std::vector<std::thread> m_threads;
std::queue<Func> m_queue;
std::mutex m_queueMutex;
std::condition_variable m_queueCond;
bool m_running = true;
};
}