Hermes
0.7.0
Linux game streaming host
Toggle main menu visibility
Loading...
Searching...
No Matches
thread_pool.h
Go to the documentation of this file.
1
5
#pragma once
6
7
// standard includes
8
#include <thread>
9
10
// local includes
11
#include "
task_pool.h
"
12
13
namespace
thread_pool_util {
17
class
ThreadPool:
public
task_pool_util::TaskPool
{
18
public
:
19
typedef
TaskPool::__task __task;
20
21
private
:
22
std::vector<std::thread> _thread;
23
24
std::condition_variable _cv;
25
std::mutex _lock;
26
27
bool
_continue;
28
29
public
:
30
ThreadPool():
31
_continue {
false
} {
32
}
33
34
explicit
ThreadPool(
int
threads):
35
_thread(threads),
36
_continue {
true
} {
37
for
(
auto
&t : _thread) {
38
t = std::thread(&ThreadPool::_main,
this
);
39
}
40
}
41
42
~ThreadPool()
noexcept
{
43
if
(!_continue) {
44
return
;
45
}
46
47
stop();
48
join();
49
}
50
51
template
<
class
Function,
class
... Args>
52
auto
push(Function &&newTask, Args &&...
args
) {
53
std::lock_guard lg(_lock);
54
auto
future = TaskPool::push(std::forward<Function>(newTask), std::forward<Args>(
args
)...);
55
56
_cv.notify_one();
57
return
future;
58
}
59
60
void
pushDelayed(std::pair<__time_point, __task> &&task) {
61
std::lock_guard lg(_lock);
62
63
TaskPool::pushDelayed(std::move(task));
64
}
65
66
template
<
class
Function,
class
X,
class
Y,
class
... Args>
67
auto
pushDelayed(Function &&newTask, std::chrono::duration<X, Y> duration, Args &&...
args
) {
68
std::lock_guard lg(_lock);
69
auto
future = TaskPool::pushDelayed(std::forward<Function>(newTask), duration, std::forward<Args>(
args
)...);
70
71
// Update all timers for wait_until
72
_cv.notify_all();
73
return
future;
74
}
75
76
void
start(
int
threads) {
77
_continue =
true
;
78
79
_thread.resize(threads);
80
81
for
(
auto
&t : _thread) {
82
t = std::thread(&ThreadPool::_main,
this
);
83
}
84
}
85
86
void
stop() {
87
std::lock_guard lg(_lock);
88
89
_continue =
false
;
90
_cv.notify_all();
91
}
92
93
void
join() {
94
for
(
auto
&t : _thread) {
95
t.join();
96
}
97
}
98
99
public
:
100
void
_main() {
101
while
(_continue) {
102
if
(
auto
task = this->pop()) {
103
(*task)->run();
104
}
else
{
105
std::unique_lock uniq_lock(_lock);
106
107
if
(ready()) {
108
continue
;
109
}
110
111
if
(!_continue) {
112
break
;
113
}
114
115
if
(
auto
tp = next()) {
116
_cv.wait_until(uniq_lock, *tp);
117
}
else
{
118
_cv.wait(uniq_lock);
119
}
120
}
121
}
122
123
// Execute remaining tasks
124
while
(
auto
task = this->pop()) {
125
(*task)->run();
126
}
127
}
128
};
129
}
// namespace thread_pool_util
task_pool_util::TaskPool
Definition
task_pool.h:47
args
Functions for handling command line arguments.
Definition
entry_handler.cpp:31
task_pool.h
Declarations for the task pool system.
src
thread_pool.h
Generated by
1.18.0