-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreadPool.h
More file actions
64 lines (57 loc) · 1.57 KB
/
ThreadPool.h
File metadata and controls
64 lines (57 loc) · 1.57 KB
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
#include <thread>
#include <mutex>
#include <queue>
#include <condition_variable>
#include <atomic>
class TaskQueue {
public:
void push(std::function<void()> task) {
std::lock_guard<std::mutex> lock(m_mutex);
m_tasks.push(task);
m_condition.notify_one();
}
std::function<void()> pop() {
std::unique_lock<std::mutex> lock(m_mutex);
m_condition.wait(lock, [this] { return !m_tasks.empty(); });
auto task = m_tasks.front();
m_tasks.pop();
return task;
}
private:
std::queue<std::function<void()>> m_tasks;
std::mutex m_mutex;
std::condition_variable m_condition;
};
class ThreadPool {
public:
ThreadPool(size_t numThreads) : m_stop(false) {
for (size_t i = 0; i < numThreads; ++i) {
m_workers.emplace_back([this] {
while (true) {
auto task = m_taskQueue.pop();
if (m_stop) return;
task();
}
});
}
}
~ThreadPool() {
{
std::lock_guard<std::mutex> lock(m_mutex);
m_stop = true;
}
m_condition.notify_all();
for (std::thread &worker : m_workers) {
worker.join();
}
}
void enqueue(std::function<void()> task) {
m_taskQueue.push(task);
}
private:
std::vector<std::thread> m_workers;
TaskQueue m_taskQueue;
std::mutex m_mutex;
std::condition_variable m_condition;
std::atomic<bool> m_stop;
};