-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtask.hpp
More file actions
417 lines (374 loc) · 10.6 KB
/
Copy pathtask.hpp
File metadata and controls
417 lines (374 loc) · 10.6 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
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
415
416
417
#pragma once
#ifdef __cpp_lib_coroutine
#include <coroutine>
#endif
#include <exception>
#include <type_traits>
#include "detail/function_result.hpp"
#include "detail/is_instance_of.hpp"
#ifdef __cpp_lib_coroutine
#include "detail/promise.hpp"
#endif
#include "detail/task_future.hpp"
#include "task_error.hpp"
#include "task_state.hpp"
namespace dispatch_queue {
#ifdef __cpp_exceptions
#define DISPATCH_QUEUE_THROW_OR(err_msg, body) throw task_error(err_msg)
#else
#define DISPATCH_QUEUE_THROW_OR(err_msg, body) body
#endif
/**
* This template class represents asynchronous tasks that run in dispatch queues.
*
* Similar to `std::shared_future`, but with the addition of support for continuations (`then`),
* checking for task state (`get_state`) and built-in C++20 coroutine support (`operator co_await`).
*
* All methods are thread-safe.
*/
template<typename T>
class task {
public:
using value_type = T;
/**
* Default-constructed tasks are invalid and don't hold any shared state.
*/
task() = default;
task(std::shared_ptr<detail::task_future<T>> future)
: future(future)
{
}
/**
* Creates a pending task.
*/
static task create_pending() {
return detail::task_future<T>::create_pending();
}
/**
* Creates a ready `task<void>`.
*/
template<typename U = T, typename = typename std::enable_if<std::is_void<U>::value>::type>
static task create_ready() {
return detail::task_future<T>::create_ready();
}
/**
* Creates a ready `task<T>` with the passed value.
*/
template<typename U = T, typename = typename std::enable_if<not std::is_void<U>::value>::type>
static task create_ready(U&& value) {
return detail::task_future<T>::create_ready(std::move(value));
}
/**
* Creates a failed `task<T>` with the passed exception.
*/
static task create_failed(std::exception_ptr exception) {
return detail::task_future<T>::create_failed(exception);
}
/**
* Checks if the task refers to a shared state.
*/
bool valid() const {
return (bool)future;
}
#ifdef __cpp_concepts
/**
* Add a continuation `f` that is guaranteed to run after this task finishes.
*
* If the task is not finished yet, `f` will run right after the task finishes in the same thread where the task ran.
* Otherwise, `f` will run immediately in the calling thread.
*
* @throw task_error Thrown when the task is invalid (`get_state() == task_state::invalid`)
*/
template<typename F>
requires (detail::is_instance_of<T, task>::value)
auto then(F&& f) const {
if (future) {
task value_this = *this;
auto nested_future = detail::task_future<detail::function_result<F, T>>::create_pending();
future->then([=] {
value_this.get().then([=](const auto& t) {
nested_future->do_work(f, t);
});
});
return to_task(nested_future);
}
else {
using future_t = detail::task_future<detail::function_result<F, T>>;
DISPATCH_QUEUE_THROW_OR("task is invalid", {
auto work = std::bind(f, T{});
auto future = future_t::create(std::move(work));
return to_task(future);
});
}
}
#endif
/**
* Add a continuation `f` that is guaranteed to run after this task finishes.
*
* If the task is not finished yet, `f` will run right after the task finishes in the same thread where the task ran.
* Otherwise, `f` will run immediately in the calling thread.
*
* @throw task_error Thrown when the task is invalid (`get_state() == task_state::invalid`)
*/
template<typename F>
auto then(F&& f) const {
if (future) {
task value_this = *this;
return to_task(future->then([=] {
return f(value_this);
}));
}
else {
using future_t = detail::task_future<detail::function_result<F, task>>;
DISPATCH_QUEUE_THROW_OR("task is invalid", {
auto work = std::bind(f, *this);
auto future = future_t::create(std::move(work));
return to_task(future);
});
}
}
/**
* Waits until the task's value is ready (by calling `wait`), then returns the stored value.
*
* @throw ... If the task failed with an exception, rethrows the exception instead.
* @throw task_error Thrown when the task is invalid (`get_state() == task_state::invalid`).
*/
T get() const {
if (future) {
return future->get();
}
else {
DISPATCH_QUEUE_THROW_OR("task is invalid", return T{});
}
}
/**
* Mark a pending task as ready.
*
* @throw task_error Thrown if task is not pending.
*/
template<typename U = T, typename = typename std::enable_if<std::is_void<U>::value>::type>
void set_value() {
if (future) {
if (!future->set_value()) {
DISPATCH_QUEUE_THROW_OR("task is not pending", return);
}
}
else {
DISPATCH_QUEUE_THROW_OR("task is invalid", return);
}
}
/**
* Mark a pending task as ready with the specified value.
*
* @throw task_error Thrown if task is not pending.
*/
template<typename U = T, typename = typename std::enable_if<not std::is_void<U>::value>::type>
void set_value(U&& value) {
if (future) {
if (!future->set_value(std::move(value))) {
DISPATCH_QUEUE_THROW_OR("task is not pending", return);
}
}
else {
DISPATCH_QUEUE_THROW_OR("task is invalid", return);
}
}
/**
* Returns the task state.
*/
task_state get_state() const {
if (future) {
return future->get_state();
}
else {
return task_state::invalid;
}
}
/**
* Returns the exception thrown while running task, if there's any.
*/
std::exception_ptr get_exception() const {
if (future) {
return future->get_exception();
}
else {
return std::make_exception_ptr(task_error("task is invalid"));
}
}
/**
* Mark a pending task as failed with the specified exception.
*
* @throw task_error Thrown if task is not pending.
*/
void set_exception(std::exception_ptr exception) {
if (future) {
if (!future->set_exception(exception)) {
DISPATCH_QUEUE_THROW_OR("task is not pending", return);
}
}
else {
DISPATCH_QUEUE_THROW_OR("task is invalid", return);
}
}
/**
* Waits until the task is either ready or failed with an exception.
*
* If the task is pending (`get_state() == task_state::pending`), blocks indefinitely until task finishes.
* Otherwise returns immediately without blocking.
*
* @throw task_error Thrown when the task is invalid (`get_state() == task_state::invalid`)
*/
void wait() const {
if (future) {
future->wait();
}
else {
DISPATCH_QUEUE_THROW_OR("task is invalid", return);
}
}
/**
* Waits for at most `timeout_duration` until the task is either ready or failed with an exception.
*
* If the task is pending (`get_state() == task_state::pending`), blocks until task finishes or until the specified `timeout_duration` has elapsed.
* Otherwise returns immediately without blocking.
*
* @returns `true` if the task is finished, otherwise `false`.
*
* @throw task_error Thrown when the task is invalid (`get_state() == task_state::invalid`)
*/
template<class Rep, class Period>
bool wait_for(const std::chrono::duration<Rep, Period>& timeout_duration) const {
if (future) {
return future->wait_for(timeout_duration);
}
else {
DISPATCH_QUEUE_THROW_OR("task is invalid", return false);
}
}
/**
* Waits until `timeout_time` has been reached or until the task is either ready or failed with an exception, whichever comes first.
*
* If the task is pending (`get_state() == task_state::pending`), blocks until task finishes or until the specified `timeout_time` has been reached.
* Otherwise returns immediately without blocking.
*
* @returns `true` if the task is finished, otherwise `false`.
*
* @throw task_error Thrown when the task is invalid (`get_state() == task_state::invalid`)
*/
template<class Clock, class Duration>
bool wait_until(const std::chrono::time_point<Clock, Duration>& timeout_time) const {
if (future) {
return future->wait_until(timeout_time);
}
else {
DISPATCH_QUEUE_THROW_OR("task is invalid", return false);
}
}
/**
* Convert valued task to void task.
*/
operator task<void>() const {
switch (get_state()) {
case task_state::pending: {
auto void_future = detail::task_future<void>::create_pending();
then([=](const task& t) {
if (auto exception = t.get_exception()) {
void_future->set_exception(exception);
}
else {
void_future->set_value();
}
});
return to_task(void_future);
}
case task_state::ready:
return task<void>::create_ready();
case task_state::failed:
return task<void>::create_failed(get_exception());
default:
return {};
}
}
/**
* Convert to task of convertible type.
*/
template<typename U, typename = typename std::enable_if<std::is_convertible<T, U>::value>::type>
explicit operator task<U>() const {
switch (get_state()) {
case task_state::pending: {
auto u_future = detail::task_future<U>::create_pending();
then([=](const task& t) {
if (auto exception = t.get_exception()) {
u_future->set_exception(exception);
}
else {
U u_value = (U) t.get();
u_future->set_value(std::move(u_value));
}
});
return to_task(u_future);
}
case task_state::ready: {
U u_value = (U) get();
return task<U>::create_ready(std::move(u_value));
}
case task_state::failed:
return task<U>::create_failed(get_exception());
default:
return {};
}
}
#ifdef __cpp_lib_coroutine
private:
class task_awaiter {
public:
task_awaiter(const task<T>& t) : t(t) {}
task_awaiter(task<T>&& t) : t(std::move(t)) {}
bool await_ready() const noexcept {
return t.get_state() != task_state::pending;
}
void await_suspend(std::coroutine_handle<> cont) const {
t.then([cont](auto&&) {
cont();
if (cont.done()) {
cont.destroy();
}
});
}
T await_resume() {
return t.get();
}
private:
task<T> t;
};
public:
/**
* Returns an awaiter that resumes coroutines on the task's continuation.
*
* @code
* dispatch_queue::task<void> my_coroutine() {
* auto task = dispatcher.dispatch([]{ ... });
* co_await task;
* do_something_after_task_finished();
* }
* @endcode
*/
task_awaiter operator co_await() const {
return task_awaiter(*this);
}
#endif // __cpp_lib_coroutine
private:
std::shared_ptr<detail::task_future<T>> future;
/// Helper function for creating a task of another type from within this class
template<typename U>
static task<U> to_task(std::shared_ptr<detail::task_future<U>> future) {
return task<U>(future);
}
};
} // end namespace dispatch_queue
#ifdef __cpp_lib_coroutine
template<typename T, typename... Args>
struct std::coroutine_traits<dispatch_queue::task<T>, Args...> {
using promise_type = dispatch_queue::detail::promise<T>;
};
#endif // __cpp_lib_coroutine