-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththread_pool.hpp
More file actions
74 lines (62 loc) · 1.34 KB
/
thread_pool.hpp
File metadata and controls
74 lines (62 loc) · 1.34 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
65
66
67
68
69
70
71
72
73
74
#ifndef _thread_pool_hpp_
#define _thread_pool_hpp_
#include <functional>
#include <list>
#include <thread>
#include "queue.hpp"
template <typename WorkItem = std::function<void ()>>
class thread_pool
{
public:
thread_pool(std::size_t capacity)
{
for (std::size_t i = 0; i < capacity; ++i)
{
m_threads.emplace_back([this]() { this->process(); });
}
}
~thread_pool()
{
disable();
for (auto & t : m_threads)
{
t.join();
}
}
void disable()
{
m_queue.disable();
}
bool execute(WorkItem item)
{
return m_queue.put(item);
}
private:
void process()
{
while (true)
{
WorkItem item;
if (!m_queue.get(item))
{
return;
}
try
{
item();
}
catch (std::exception & e)
{
fprintf(stderr, "caught an exception while executing on a thread pool\n%s\n", e.what());
}
catch (...)
{
fprintf(stderr, "caught an unknown exception while executing on a thread pool\n");
}
}
}
private:
std::list<std::thread> m_threads;
queue<WorkItem> m_queue;
};
#endif // _thread_pool_hpp_