-
Notifications
You must be signed in to change notification settings - Fork 2
/
taskqueue.cpp
414 lines (337 loc) · 6.75 KB
/
taskqueue.cpp
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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
#include "taskqueue.h"
#include "asserts.h"
#include <stdexcept>
namespace Task {
template<bool enabled>
struct QueueI13n;
template<>
struct QueueI13n<false>
{
template<typename ...A>
static void out(A&& ...) {}
};
template<>
struct QueueI13n<true>
{
private:
static void raw()
{
}
template<typename T1>
static void raw(T1&& first)
{
std::cout << std::forward<T1>(first);
}
template<typename T1, typename ...A>
static void raw(T1&& first, A&& ...rest)
{
raw(std::forward<T1>(first));
raw(std::forward<A>(rest)...);
}
public:
template<typename ...A>
static void out(A&& ...args)
{
raw("QUEUE: ", std::forward<A>(args)...);
std::cout << std::endl;
}
};
typedef QueueI13n<false> Instr;
Queue::Queue(int workerCount)
: done(false)
{
start(workerCount);
}
Queue::~Queue()
{
stop();
}
void Queue::start(int workerCount)
{
// One worker thread per CPU
if (workerCount < 0)
workerCount = int(std::thread::hardware_concurrency());
// Start thread(s)
for (auto i = 0; i < workerCount; ++i)
workers.emplace_back(&Queue::workLoop, this);
}
void Queue::stop()
{
ScopedLock lock(queueLock);
done = true;
lock.unlock();
notEmpty.notify_all();
for (auto i = workers.begin(), e = workers.end(); i != e; ++i)
i->join();
workers.clear();
}
Queue &Queue::global()
{
static Queue instance;
return instance;
}
Handle Queue::run(Task::callback work, bool highPriority)
{
return global().queueWork(std::move(work), highPriority);
}
Handle Queue::queueWork(Task::callback callback, bool highPriority)
{
auto task = std::make_shared<Task>(std::move(callback));
ScopedLock lock(queueLock);
if (!highPriority)
queue.emplace_back(task);
else
queue.emplace_front(task);
lock.unlock();
notEmpty.notify_one();
return Handle(std::move(task));
}
When Queue::runMultiple(std::function<bool(Task::callback&)> generator, bool highPriority)
{
typedef std::vector<TaskPointer> TaskPointerList;
typedef std::vector<Handle> HandleList;
TaskPointerList tasks;
HandleList handles;
Task::callback item;
while (generator(item))
{
auto task = std::make_shared<Task>(std::move(item));
tasks.emplace_back(task);
handles.emplace_back(std::move(task));
}
ScopedLock lock(queueLock);
if (!highPriority)
{
std::copy(std::move_iterator<TaskPointerList::iterator>(std::begin(tasks)),
std::move_iterator<TaskPointerList::iterator>(std::end(tasks)),
std::back_inserter(queue));
}
else
{
std::copy(std::move_iterator<TaskPointerList::reverse_iterator>(tasks.rbegin()),
std::move_iterator<TaskPointerList::reverse_iterator>(tasks.rend()),
std::front_inserter(queue));
}
lock.unlock();
notEmpty.notify_all();
return When(std::begin(handles), std::end(handles));
}
bool Queue::getMoreWork(TaskPointer &item)
{
ScopedLock lock(queueLock);
notEmpty.wait(lock, [this] { return !queue.empty() || done; });
if (!done) {
item = std::move(queue.front());
queue.pop_front();
Instr::out("QUEUE: took task");
if (queue.empty())
Instr::out("QUEUE: emptied");
}
return !done;
}
void Queue::workLoop()
{
TaskPointer item;
while (getMoreWork(item))
{
Instr::out("Started work");
item->invoke();
Instr::out("Finished work");
// Release the object so we don't keep it alive while waiting
item.reset();
}
}
Task::Task(Task::callback func)
: func(std::move(func))
, done(false)
{
}
void Task::invoke()
{
func();
CallbackList thensSnapshot;
ScopedLock lock(taskLock);
done = true;
thensSnapshot.swap(thens);
lock.unlock();
taskCond.notify_all();
// Run all of the then callbacks
run(thensSnapshot.begin(), thensSnapshot.end(), true);
}
void Task::wait()
{
ScopedLock lock(taskLock);
taskCond.wait(lock, [this]() { return done; });
}
bool Task::wait_for(int64_t milliseconds)
{
ScopedLock lock(taskLock);
if (milliseconds <= 0)
return done;
if (done)
return true;
return taskCond.wait_for(lock,
std::chrono::milliseconds(milliseconds),
[this]() { return done; });
}
void Task::then(std::function<void()> func)
{
ScopedLock lock(taskLock);
// If the task isn't done, register for callback
// Otherwise, just immediately call the handler
if (!done)
thens.emplace_back(std::move(func));
else
func();
}
Handle::Handle()
: task(nullptr)
{
}
Handle::Handle(std::shared_ptr<Task> task)
: task(std::move(task))
{
}
Handle::Handle(const Handle& r)
: task(r.task)
{
}
Handle::Handle(Handle&& r)
: task(std::move(r.task))
{
}
Handle& Handle::operator =(Handle r)
{
task = std::move(r.task);
return *this;
}
void Handle::release()
{
task = nullptr;
}
bool Handle::empty() const
{
return task == nullptr;
}
Handle& Handle::then(Task::callback func)
{
task->then(std::move(func));
return *this;
}
Handle& Handle::wait()
{
if (task)
{
task->wait();
return *this;
}
throw std::logic_error("Attempt to wait for empty Task::Handle");
}
bool Handle::wait_for(int64_t milliseconds)
{
if (task)
return task->wait_for(milliseconds);
throw std::logic_error("Attempt to wait for empty Task::Handle");
}
WhenImpl& WhenImpl::then(Task::callback func)
{
if (got < expect)
thens.emplace_back(std::move(func));
else
func();
return *this;
}
void WhenImpl::wait()
{
ScopedLock lock(*whenLock);
if (got < expect)
whenCond->wait(lock, [this] { return !(got < expect); });
}
bool WhenImpl::wait_for(int64_t milliseconds)
{
ScopedLock lock(*whenLock);
if (got < expect)
return whenCond->wait_for(lock, std::chrono::milliseconds(milliseconds),
[this] { return !(got < expect); });
return true;
}
void WhenImpl::addref()
{
++refcount;
}
void WhenImpl::release()
{
if (--refcount == 0)
delete this;
}
void WhenImpl::beginAdding()
{
ScopedLock lock(*whenLock);
++expect;
}
void WhenImpl::endAdding()
{
// Signal releases a reference so balance that here
addref();
signal();
}
WhenImpl& WhenImpl::add()
{
return *this;
}
void WhenImpl::signal()
{
ScopedLock lock(*whenLock);
AssertBreakGreater(expect, 0);
auto newGot = ++got;
AssertBreakLEqual(newGot, expect);
if (newGot == expect)
{
Task::CallbackList thensSnapshot;
thensSnapshot.swap(thens);
lock.unlock();
// If the condition variable has been created, notify it
if (whenCond)
whenCond->notify_all();
// Call all then callbacks
run(thensSnapshot.begin(), thensSnapshot.end(), true);
}
AssertBreakLEqual(got, expect);
release();
}
When::When(When const& r)
: ptr(r.ptr)
{
if (r.ptr != nullptr)
r.ptr->addref();
}
When::When(When&& r)
: ptr(r.ptr)
{
r.ptr = nullptr;
}
When::~When()
{
if (ptr != nullptr)
ptr->release();
}
When& When::operator=(When r)
{
std::swap(ptr, r.ptr);
return *this;
}
When& When::then(Task::callback func)
{
ptr->then(std::move(func));
return *this;
}
When& When::wait()
{
ptr->wait();
return *this;
}
bool When::wait_for(int64_t milliseconds)
{
return ptr->wait_for(milliseconds);
}
}