-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathThreadPool.h
111 lines (92 loc) · 2.29 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
110
111
#pragma once
#include <thread>
#include <vector>
#include <queue>
#include <mutex>
#include <condition_variable>
#include <functional>
#include <future>
#include <atomic>
#include <type_traits>
#include <typeinfo>
/* ThreadPool class */
class ThreadPool
{
public:
ThreadPool()
{
m_shutdown.store(false, std::memory_order_relaxed);
//m_shutdown = false;
createThreads(1);
}
ThreadPool(std::size_t numThreads)
{
m_shutdown.store(false, std::memory_order_relaxed);
//m_shutdown = false;
createThreads(numThreads);
}
~ThreadPool()
{
m_shutdown.store(true, std::memory_order_relaxed);
//m_shutdown = true;
m_notifier.notify_all();
for (std::thread& th : m_threads)
{
th.join();
}
}
//add any arg # function to queue
template <typename Func, typename... Args>
auto enqueue(Func&& f, Args&&... args)
{
//get return type of the function
using RetType = std::invoke_result_t<Func, Args...>;
auto task = std::make_shared<std::packaged_task<RetType()>>([&f, &args...]() { return f(std::forward<Args>(args)...); });
{
// lock jobQueue mutex, add job to the job queue
std::scoped_lock<std::mutex> lock(m_jobMutex);
//place the job into the queue
m_jobQueue.emplace([task]() {
(*task)();
});
}
m_notifier.notify_one();
return task->get_future();
}
/* utility functions */
std::size_t getThreadCount() const {
return m_threads.size();
}
private:
using Job = std::function<void()>;
std::vector<std::thread> m_threads;
std::queue<Job> m_jobQueue;
std::condition_variable m_notifier;
std::mutex m_jobMutex;
std::atomic<bool> m_shutdown;
void createThreads(std::size_t numThreads)
{
m_threads.reserve(numThreads);
for (int i = 0; i != numThreads; ++i)
{
m_threads.emplace_back(std::thread([this]()
{
while (true)
{
Job job;
{
std::unique_lock<std::mutex> lock(m_jobMutex);
m_notifier.wait(lock, [this] {return !m_jobQueue.empty() || m_shutdown.load(std::memory_order_relaxed); });
if (m_shutdown.load(std::memory_order_relaxed))
{
break;
}
job = std::move(m_jobQueue.front());
m_jobQueue.pop();
}
job();
}
}));
}
}
}; /* end ThreadPool Class */