-
Notifications
You must be signed in to change notification settings - Fork 1
/
workqueuebase.h
149 lines (119 loc) · 3.09 KB
/
workqueuebase.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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
#ifndef JWUTIL_WORKQUEUEBASE_H
#define JWUTIL_WORKQUEUEBASE_H
#include <array>
#include <tuple>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <queue>
#include "methodcallback.h"
namespace jw_util
{
template <typename Derived, unsigned int num_threads, typename... ArgTypes>
class WorkQueueBase
{
public:
struct construct_paused_t {};
static constexpr construct_paused_t construct_paused {};
WorkQueueBase(jw_util::MethodCallback<ArgTypes...> worker)
: worker(worker)
, running(false)
{
start();
}
WorkQueueBase(jw_util::MethodCallback<ArgTypes...> worker, construct_paused_t)
: worker(worker)
, running(false)
{}
~WorkQueueBase()
{
if (running)
{
pause();
}
}
void push(ArgTypes... args)
{
assert(running);
if (num_threads)
{
{
std::lock_guard<std::mutex> lock(mutex);
(void) lock;
queue.emplace(std::forward<ArgTypes>(args)...);
}
conditional_variable.notify_one();
}
else
{
worker.call(std::forward<ArgTypes>(args)...);
}
}
void start()
{
assert(!running);
running = true;
for (unsigned int i = 0; i < num_threads; i++)
{
threads[i] = std::thread(&WorkQueueBase<Derived, num_threads, ArgTypes...>::loop, this);
}
}
void pause()
{
assert(running);
{
std::lock_guard<std::mutex> lock(mutex);
(void) lock;
running = false;
}
conditional_variable.notify_all();
for (unsigned int i = 0; i < num_threads; i++)
{
threads[i].join();
}
}
protected:
typedef std::tuple<typename std::remove_reference<ArgTypes>::type...> TupleType;
const jw_util::MethodCallback<ArgTypes...> worker;
std::array<std::thread, num_threads> threads;
std::mutex mutex;
std::condition_variable conditional_variable;
std::queue<TupleType> queue;
bool running;
void loop()
{
assert(num_threads);
std::unique_lock<std::mutex> lock(mutex);
while (true)
{
if (queue.empty())
{
if (!running) {break;}
get_derived()->wait(lock);
}
else
{
TupleType args = std::move(queue.front());
queue.pop();
lock.unlock();
dispatch(std::move(args));
lock.lock();
}
}
}
void dispatch(TupleType &&args)
{
call(std::forward<TupleType>(args), std::index_sequence_for<ArgTypes...>{});
}
template<std::size_t... Indices>
void call(TupleType &&args, std::index_sequence<Indices...>)
{
worker.call(std::forward<ArgTypes>(std::get<Indices>(std::forward<TupleType>(args)))...);
}
Derived *get_derived()
{
return static_cast<Derived *>(this);
}
};
}
#endif // JWUTIL_WORKQUEUEBASE_H