-
Notifications
You must be signed in to change notification settings - Fork 182
/
async_scope.hpp
473 lines (399 loc) · 15 KB
/
async_scope.hpp
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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License Version 2.0 with LLVM Exceptions
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* https://llvm.org/LICENSE.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <unifex/config.hpp>
#include <unifex/async_manual_reset_event.hpp>
#include <unifex/get_stop_token.hpp>
#include <unifex/inplace_stop_token.hpp>
#include <unifex/just_from.hpp>
#include <unifex/let_value_with.hpp>
#include <unifex/let_value_with_stop_source.hpp>
#include <unifex/let_value_with_stop_token.hpp>
#include <unifex/manual_lifetime.hpp>
#include <unifex/nest.hpp>
#include <unifex/on.hpp>
#include <unifex/receiver_concepts.hpp>
#include <unifex/scheduler_concepts.hpp>
#include <unifex/sender_concepts.hpp>
#include <unifex/sequence.hpp>
#include <unifex/spawn_detached.hpp>
#include <unifex/spawn_future.hpp>
#include <unifex/then.hpp>
#include <unifex/type_traits.hpp>
#include <unifex/v2/async_scope.hpp>
#include <algorithm>
#include <atomic>
#include <memory>
#include <tuple>
#include <unifex/detail/prologue.hpp>
namespace unifex {
inline namespace v1 {
namespace _async_scope {
template <typename Receiver>
struct _attach_op_base final {
struct type;
};
template <typename Receiver>
struct _attach_op_base<Receiver>::type {
template <typename Receiver2>
explicit type(inplace_stop_token stoken, Receiver2&& receiver) noexcept(
std::is_nothrow_constructible_v<Receiver, Receiver2>)
: stoken_(stoken)
, receiver_(static_cast<Receiver2&&>(receiver)) {}
type(type&&) = delete;
~type() = default;
void construct_stop_callbacks() noexcept {
stokenCallback_.construct(stoken_, stop_callback{this});
receiverCallback_.construct(get_stop_token(receiver_), stop_callback{this});
}
void request_stop() noexcept {
// try to increment the refcount from 1 to 2
std::size_t expected{1};
if (!refcount_.compare_exchange_strong(
expected, 2, std::memory_order_relaxed)) {
// we didn't get to increment from one to two so either the count was
// already zero because the operation is already complete, or the count
// was two because we're the second stop callback; in either case, we
// should just no-op
UNIFEX_ASSERT(expected == 0 || expected == 2);
return;
}
stopSource_.request_stop();
if (auto receiver = try_complete()) {
unifex::set_done(std::move(*receiver));
}
}
Receiver* try_complete() noexcept {
// decrement refcount and check the old count
if (refcount_.fetch_sub(1, std::memory_order_acq_rel) == 1) {
// the old count was one so we've won the race to be the completer
receiverCallback_.destruct();
stokenCallback_.destruct();
return &receiver_;
}
return nullptr;
}
struct stop_callback {
type* op_;
void operator()() noexcept { op_->request_stop(); }
};
using stoken_callback_t =
typename inplace_stop_token::template callback_type<stop_callback>;
using receiver_stoken_t = stop_token_type_t<Receiver>;
using receiver_callback_t =
typename receiver_stoken_t::template callback_type<stop_callback>;
inplace_stop_token stoken_;
std::atomic<std::size_t> refcount_{1};
inplace_stop_source stopSource_;
manual_lifetime<stoken_callback_t> stokenCallback_;
UNIFEX_NO_UNIQUE_ADDRESS manual_lifetime<receiver_callback_t>
receiverCallback_;
UNIFEX_NO_UNIQUE_ADDRESS Receiver receiver_;
};
template <typename Sender, typename Receiver>
struct _attach_op final {
struct type;
};
template <typename Receiver>
struct _attach_receiver final {
struct type;
};
template <typename Receiver>
struct _attach_receiver<Receiver>::type final {
template <typename... T>
void set_value(T... values) noexcept {
if (auto receiver = op_->try_complete()) {
UNIFEX_TRY {
unifex::set_value(std::move(*receiver), std::move(values)...);
}
UNIFEX_CATCH(...) {
unifex::set_error(std::move(*receiver), std::current_exception());
}
}
}
template <typename E>
void set_error(E e) noexcept {
if (auto receiver = op_->try_complete()) {
unifex::set_error(std::move(*receiver), std::move(e));
}
}
void set_done() noexcept {
if (auto receiver = op_->try_complete()) {
unifex::set_done(std::move(*receiver));
}
}
friend inplace_stop_token
tag_invoke(tag_t<get_stop_token>, const type& r) noexcept {
return r.op_->stopSource_.get_token();
}
template(typename CPO) //
(requires is_receiver_query_cpo_v<CPO>) //
friend auto tag_invoke(CPO&& cpo, const type& r) noexcept
-> decltype(std::forward<CPO>(cpo)(std::declval<const Receiver&>())) {
return std::forward<CPO>(cpo)(r.op_->receiver_);
}
typename _attach_op_base<Receiver>::type* op_;
};
template <typename Sender, typename Receiver>
struct _attach_op<Sender, Receiver>::type final
: _attach_op_base<Receiver>::type {
using base_t = typename _attach_op_base<Receiver>::type;
using receiver_t = typename _attach_receiver<Receiver>::type;
using op_t = connect_result_t<Sender, receiver_t>;
template <typename Sender2, typename Receiver2>
explicit type(
inplace_stop_token stoken,
Sender2&& sender,
Receiver2&& receiver) noexcept(std::
is_nothrow_constructible_v<
base_t,
inplace_stop_token&,
Receiver2>&&
is_nothrow_connectable_v<
Sender2,
receiver_t>)
: base_t{stoken, static_cast<Receiver2&&>(receiver)}
, op_(connect(static_cast<Sender2&&>(sender), receiver_t{this})) {}
type(type&&) = delete;
~type() = default;
friend void tag_invoke(tag_t<start>, type& op) noexcept {
op.construct_stop_callbacks();
unifex::start(op.op_);
}
op_t op_;
};
template <typename Sender>
struct _attach_sender final {
struct type;
};
template <typename Sender>
struct _attach_sender<Sender>::type final {
template <
template <typename...>
typename Variant,
template <typename...>
typename Tuple>
using value_types = sender_value_types_t<Sender, Variant, Tuple>;
template <template <typename...> class Variant>
using error_types = typename concat_type_lists_unique_t<
sender_error_types_t<Sender, type_list>,
type_list<std::exception_ptr>>::template apply<Variant>;
static constexpr bool sends_done = sender_traits<Sender>::sends_done;
static constexpr blocking_kind blocking =
std::min(blocking_kind::maybe(), sender_traits<Sender>::blocking());
static constexpr bool is_always_scheduler_affine =
sender_traits<Sender>::is_always_scheduler_affine;
template <typename Sender2>
explicit type(inplace_stop_token stoken, Sender2&& sender) noexcept(
std::is_nothrow_constructible_v<Sender, Sender2>)
: stoken_(stoken)
, sender_(static_cast<Sender2&&>(sender)) {}
template <typename Receiver>
using op_t = typename _attach_op<Sender, remove_cvref_t<Receiver>>::type;
template(typename Sender2, typename Receiver) //
(requires same_as<remove_cvref_t<Sender2>, type>) //
friend auto tag_invoke(
tag_t<connect>,
Sender2&& sender,
Receiver&& receiver) noexcept(std::
is_nothrow_constructible_v<
op_t<Receiver>,
inplace_stop_token,
member_t<Sender2, Sender>,
Receiver>) -> op_t<Receiver> {
return op_t<Receiver>{
sender.stoken_,
static_cast<Sender2&&>(sender).sender_,
static_cast<Receiver&&>(receiver)};
}
friend constexpr blocking_kind tag_invoke(
tag_t<unifex::blocking>, [[maybe_unused]] const type& self) noexcept {
if constexpr (
sender_traits<Sender>::blocking == blocking_kind::always_inline) {
// we can be constexpr in this case
return blocking_kind::always_inline;
} else {
if (self.scope_) {
return unifex::blocking(self.sender_);
} else {
// we complete inline with done when there's no scope
return blocking_kind::always_inline;
}
}
}
private:
inplace_stop_token stoken_;
UNIFEX_NO_UNIQUE_ADDRESS Sender sender_;
};
struct async_scope {
/**
* Connects and starts the given Sender, returning a future<> with which you
* can observe the result.
*/
template <typename Sender>
auto spawn(Sender&& sender)
-> decltype(spawn_future(static_cast<Sender&&>(sender), *this)) {
return spawn_future(static_cast<Sender&&>(sender), *this);
}
/**
* Equivalent to spawn(on((Scheduler&&) scheduler, (Sender&&)sender)).
*/
template(typename Sender, typename Scheduler) //
(requires scheduler<Scheduler>) //
auto spawn_on(Scheduler&& scheduler, Sender&& sender)
-> decltype(spawn(on((Scheduler &&) scheduler, (Sender &&) sender))) {
return spawn(on((Scheduler &&) scheduler, (Sender &&) sender));
}
/**
* Equivalent to spawn_on((Scheduler&&)scheduler, just_from((Fun&&)fun)).
*/
template(typename Scheduler, typename Fun) //
(requires scheduler<Scheduler> AND std::is_invocable_v<Fun>) //
auto spawn_call_on(Scheduler&& scheduler, Fun&& fun) {
return spawn_on((Scheduler &&) scheduler, just_from((Fun &&) fun));
}
/**
* Connects and starts the given Sender with no way to observe the result.
*
* Invokes std::terminate() if the resulting operation completes with an
* error.
*/
template <typename Sender>
auto detached_spawn(Sender&& sender)
-> decltype(spawn_detached(static_cast<Sender&&>(sender), *this)) {
spawn_detached(static_cast<Sender&&>(sender), *this);
}
/**
* Equivalent to detached_spawn(on((Scheduler&&) scheduler,
* (Sender&&)sender)).
*/
template(typename Sender, typename Scheduler) //
(requires scheduler<Scheduler>) //
auto detached_spawn_on(Scheduler&& scheduler, Sender&& sender)
-> decltype(detached_spawn(
on((Scheduler &&) scheduler, (Sender &&) sender))) {
detached_spawn(on((Scheduler &&) scheduler, (Sender &&) sender));
}
/**
* Equivalent to detached_spawn_on((Scheduler&&)scheduler,
* just_from((Fun&&)fun)).
*/
template(typename Scheduler, typename Fun) //
(requires scheduler<Scheduler> AND std::is_invocable_v<Fun>) //
void detached_spawn_call_on(Scheduler&& scheduler, Fun&& fun) {
static_assert(
std::is_nothrow_invocable_v<Fun>,
"Please annotate your invocable with noexcept.");
detached_spawn_on((Scheduler &&) scheduler, just_from((Fun &&) fun));
}
/**
* Returns a _Sender_ that, when connected and started,
* connects and starts the given Sender.
*
* Returned _Sender_ owns a reference to this async_scope.
*/
template <typename Sender>
[[nodiscard]] auto attach(Sender&& sender) noexcept(
std::is_nothrow_constructible_v<remove_cvref_t<Sender>, Sender>) {
using attach_sender_t =
typename _attach_sender<remove_cvref_t<Sender>>::type;
return nest(
attach_sender_t{stopSource_.get_token(), static_cast<Sender&&>(sender)},
scope_);
}
/**
* Equivalent to attach(just_from((Fun&&)fun)).
*/
template(typename Fun) //
(requires std::is_invocable_v<Fun>) //
[[nodiscard]] auto attach_call(Fun&& fun) noexcept(
noexcept(attach(just_from((Fun &&) fun)))) {
return attach(just_from((Fun &&) fun));
}
/**
* Equivalent to attach(on((Scheduler&&) scheduler, (Sender&&)sender)).
*/
template(typename Sender, typename Scheduler) //
(requires scheduler<Scheduler> AND sender<Sender>) //
[[nodiscard]] auto attach_on(Scheduler&& scheduler, Sender&& sender) noexcept(
noexcept(attach(on((Scheduler &&) scheduler, (Sender &&) sender)))) {
return attach(on((Scheduler &&) scheduler, (Sender &&) sender));
}
/**
* Equivalent to attach_on((Scheduler&&)scheduler, just_from((Fun&&)fun)).
*/
template(typename Scheduler, typename Fun) //
(requires scheduler<Scheduler> AND std::is_invocable_v<Fun>) //
[[nodiscard]] auto attach_call_on(Scheduler&& scheduler, Fun&& fun) noexcept(
noexcept(
attach_on((Scheduler &&) scheduler, just_from((Fun &&) fun)))) {
return attach_on((Scheduler &&) scheduler, just_from((Fun &&) fun));
}
/**
* Returns a Sender that, when connected and started, marks the scope so that
* no more work can be spawned within it. The returned Sender completes when
* the last outstanding operation spawned within the scope completes.
*/
[[nodiscard]] auto complete() noexcept { return scope_.join(); }
/**
* Returns a Sender that, when connected and started, marks the scope so that
* no more work can be spawned within it and requests cancellation of all
* outstanding work. The returned Sender completes when the last outstanding
* operation spawned within the scope completes.
*
* Equivalent to, but more efficient than, invoking request_stop() and then
* connecting and starting the result of complete().
*/
[[nodiscard]] auto cleanup() noexcept {
return sequence(
just_from([this]() noexcept { request_stop(); }), scope_.join());
}
/**
* Returns a stop token from the scope's internal stop source.
*/
inplace_stop_token get_stop_token() noexcept {
return stopSource_.get_token();
}
/**
* Marks the scope so that no more work can be spawned within it and requests
* cancellation of all outstanding work.
*/
void request_stop() noexcept {
scope_.end_scope();
stopSource_.request_stop();
}
private:
inplace_stop_source stopSource_;
unifex::v2::async_scope scope_;
template(typename Sender, typename Scope) //
(requires same_as<async_scope&, Scope&>) //
friend auto tag_invoke(
tag_t<nest>,
Sender&& sender,
Scope& scope) noexcept(noexcept(scope
.attach(static_cast<Sender&&>(
sender))))
-> decltype(scope.attach(static_cast<Sender&&>(sender))) {
return scope.attach(static_cast<Sender&&>(sender));
}
};
} // namespace _async_scope
using v1::_async_scope::async_scope;
template <typename... Ts>
using future = unifex::v2::future<unifex::v1::async_scope, Ts...>;
} // namespace v1
} // namespace unifex
#include <unifex/detail/epilogue.hpp>