-
Notifications
You must be signed in to change notification settings - Fork 246
/
Copy pathbase_coroutine_threadpool.h
701 lines (596 loc) · 19.9 KB
/
base_coroutine_threadpool.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
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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
namespace winrt::impl
{
inline auto submit_threadpool_callback(void(__stdcall* callback)(void*, void* context), void* context)
{
if (!WINRT_IMPL_TrySubmitThreadpoolCallback(callback, context, nullptr))
{
throw_last_error();
}
}
inline void __stdcall resume_background_callback(void*, void* context) noexcept
{
coroutine_handle<>::from_address(context)();
};
inline auto resume_background(coroutine_handle<> handle)
{
submit_threadpool_callback(resume_background_callback, handle.address());
}
inline std::pair<int32_t, int32_t> get_apartment_type() noexcept
{
int32_t aptType;
int32_t aptTypeQualifier;
if (0 == WINRT_IMPL_CoGetApartmentType(&aptType, &aptTypeQualifier))
{
return { aptType, aptTypeQualifier };
}
else
{
return { 1 /* APTTYPE_MTA */, 1 /* APTTYPEQUALIFIER_IMPLICIT_MTA */ };
}
}
inline bool is_sta_thread() noexcept
{
auto type = get_apartment_type();
switch (type.first)
{
case 0: /* APTTYPE_STA */
case 3: /* APTTYPE_MAINSTA */
return true;
case 2: /* APTTYPE_NA */
return type.second == 3 /* APTTYPEQUALIFIER_NA_ON_STA */ ||
type.second == 5 /* APTTYPEQUALIFIER_NA_ON_MAINSTA */;
}
return false;
}
struct resume_apartment_context
{
resume_apartment_context() = default;
resume_apartment_context(std::nullptr_t) : m_context(nullptr), m_context_type(-1) {}
bool valid() const noexcept
{
return m_context_type.value >= 0;
}
com_ptr<IContextCallback> m_context = try_capture<IContextCallback>(WINRT_IMPL_CoGetObjectContext);
movable_primitive<int32_t, -1> m_context_type = get_apartment_type().first;
};
inline int32_t __stdcall resume_apartment_callback(com_callback_args* args) noexcept
{
coroutine_handle<>::from_address(args->data)();
return 0;
};
[[nodiscard]] inline bool resume_apartment_sync(com_ptr<IContextCallback> const& context, coroutine_handle<> handle, int32_t* failure)
{
com_callback_args args{};
args.data = handle.address();
auto result = context->ContextCallback(resume_apartment_callback, &args, guid_of<ICallbackWithNoReentrancyToApplicationSTA>(), 5, nullptr);
if (result < 0)
{
// Resume the coroutine on the wrong apartment, but tell it why.
*failure = result;
return false;
}
return true;
}
struct threadpool_resume
{
threadpool_resume(com_ptr<IContextCallback> const& context, coroutine_handle<> handle, int32_t* failure) :
m_context(context), m_handle(handle), m_failure(failure) { }
com_ptr<IContextCallback> m_context;
coroutine_handle<> m_handle;
int32_t* m_failure;
};
inline void __stdcall fallback_submit_threadpool_callback(void*, void* p) noexcept
{
std::unique_ptr<threadpool_resume> state{ static_cast<threadpool_resume*>(p) };
if (!resume_apartment_sync(state->m_context, state->m_handle, state->m_failure))
{
state->m_handle.resume();
}
}
inline void resume_apartment_on_threadpool(com_ptr<IContextCallback> const& context, coroutine_handle<> handle, int32_t* failure)
{
auto state = std::make_unique<threadpool_resume>(context, handle, failure);
submit_threadpool_callback(fallback_submit_threadpool_callback, state.get());
state.release();
}
[[nodiscard]] inline auto resume_apartment(resume_apartment_context const& context, coroutine_handle<> handle, int32_t* failure)
{
WINRT_ASSERT(context.valid());
if ((context.m_context == nullptr) || (context.m_context == try_capture<IContextCallback>(WINRT_IMPL_CoGetObjectContext)))
{
return false;
}
else if (context.m_context_type.value == 1 /* APTTYPE_MTA */)
{
resume_background(handle);
return true;
}
else if (is_sta_thread())
{
resume_apartment_on_threadpool(context.m_context, handle, failure);
return true;
}
else
{
return resume_apartment_sync(context.m_context, handle, failure);
}
}
}
WINRT_EXPORT namespace winrt
{
struct cancellable_promise
{
using canceller_t = void(*)(void*);
void set_canceller(canceller_t canceller, void* context)
{
m_context = context;
m_canceller.store(canceller, std::memory_order_release);
}
void revoke_canceller()
{
while (m_canceller.exchange(nullptr, std::memory_order_acquire) == cancelling_ptr)
{
std::this_thread::yield();
}
}
void cancel()
{
auto canceller = m_canceller.exchange(cancelling_ptr, std::memory_order_acquire);
struct unique_cancellation_lock
{
cancellable_promise* promise;
~unique_cancellation_lock()
{
promise->m_canceller.store(nullptr, std::memory_order_release);
}
} lock{ this };
if ((canceller != nullptr) && (canceller != cancelling_ptr))
{
canceller(m_context);
}
}
bool enable_cancellation_propagation(bool value) noexcept
{
return std::exchange(m_propagate_cancellation, value);
}
bool cancellation_propagation_enabled() const noexcept
{
return m_propagate_cancellation;
}
private:
static inline auto const cancelling_ptr = reinterpret_cast<canceller_t>(1);
std::atomic<canceller_t> m_canceller{ nullptr };
void* m_context{ nullptr };
bool m_propagate_cancellation{ false };
};
template <typename Derived>
struct cancellable_awaiter
{
cancellable_awaiter() noexcept = default;
cancellable_awaiter(cancellable_awaiter const&) = default;
~cancellable_awaiter()
{
if (m_promise)
{
m_promise->revoke_canceller();
}
}
void operator=(cancellable_awaiter const&) = delete;
protected:
template <typename T>
void set_cancellable_promise_from_handle(impl::coroutine_handle<T> const& handle)
{
if constexpr (std::is_base_of_v<cancellable_promise, T>)
{
set_cancellable_promise(&handle.promise());
}
}
private:
void set_cancellable_promise(cancellable_promise* promise)
{
if (promise->cancellation_propagation_enabled())
{
m_promise = promise;
static_cast<Derived*>(this)->enable_cancellation(m_promise);
}
}
cancellable_promise* m_promise = nullptr;
};
}
WINRT_EXPORT namespace winrt
{
[[nodiscard]] inline auto resume_background() noexcept
{
struct awaitable
{
bool await_ready() const noexcept
{
return false;
}
void await_resume() const noexcept
{
}
void await_suspend(impl::coroutine_handle<> handle) const
{
impl::resume_background(handle);
}
};
return awaitable{};
}
template <typename T>
[[nodiscard]] auto resume_background(T const& context) noexcept
{
struct awaitable
{
awaitable(T const& context) : m_context(context)
{
}
bool await_ready() const noexcept
{
return false;
}
void await_resume() const noexcept
{
}
void await_suspend(impl::coroutine_handle<> resume)
{
m_resume = resume;
if (!WINRT_IMPL_TrySubmitThreadpoolCallback(callback, this, nullptr))
{
throw_last_error();
}
}
private:
static void __stdcall callback(void*, void* context) noexcept
{
auto that = static_cast<awaitable*>(context);
auto guard = that->m_context();
that->m_resume();
}
T const& m_context;
impl::coroutine_handle<> m_resume{ nullptr };
};
return awaitable{ context };
}
struct apartment_context
{
apartment_context() = default;
apartment_context(std::nullptr_t) : context(nullptr) { }
operator bool() const noexcept { return context.valid(); }
bool operator!() const noexcept { return !context.valid(); }
impl::resume_apartment_context context;
};
}
namespace winrt::impl
{
struct apartment_awaiter
{
apartment_context const& context;
int32_t failure = 0;
bool await_ready() const noexcept
{
return false;
}
void await_resume() const
{
check_hresult(failure);
}
bool await_suspend(impl::coroutine_handle<> handle)
{
auto context_copy = context;
return impl::resume_apartment(context_copy.context, handle, &failure);
}
};
struct timespan_awaiter : cancellable_awaiter<timespan_awaiter>
{
explicit timespan_awaiter(Windows::Foundation::TimeSpan duration) noexcept :
m_duration(duration)
{
}
#if defined(__GNUC__) && !defined(__clang__)
// HACK: GCC seems to require a move when calling operator co_await
// on the return value of resume_after.
// This might be related to upstream bug:
// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=99575
timespan_awaiter(timespan_awaiter &&other) noexcept :
m_timer{std::move(other.m_timer)},
m_duration{std::move(other.m_duration)},
m_handle{std::move(other.m_handle)},
m_state{other.m_state.load()}
{}
#endif
void enable_cancellation(cancellable_promise* promise)
{
promise->set_canceller([](void* context)
{
auto that = static_cast<timespan_awaiter*>(context);
if (that->m_state.exchange(state::canceled, std::memory_order_acquire) == state::pending)
{
that->fire_immediately();
}
}, this);
}
bool await_ready() const noexcept
{
return m_duration.count() <= 0;
}
template <typename T>
void await_suspend(impl::coroutine_handle<T> handle)
{
set_cancellable_promise_from_handle(handle);
m_handle = handle;
create_threadpool_timer();
}
void await_resume()
{
if (m_state.exchange(state::idle, std::memory_order_relaxed) == state::canceled)
{
throw hresult_canceled();
}
}
private:
void create_threadpool_timer()
{
m_timer.attach(check_pointer(WINRT_IMPL_CreateThreadpoolTimer(callback, this, nullptr)));
int64_t relative_count = -m_duration.count();
WINRT_IMPL_SetThreadpoolTimer(m_timer.get(), &relative_count, 0, 0);
state expected = state::idle;
if (!m_state.compare_exchange_strong(expected, state::pending, std::memory_order_release))
{
fire_immediately();
}
}
void fire_immediately() noexcept
{
if (WINRT_IMPL_SetThreadpoolTimerEx(m_timer.get(), nullptr, 0, 0))
{
int64_t now = 0;
WINRT_IMPL_SetThreadpoolTimer(m_timer.get(), &now, 0, 0);
}
}
static void __stdcall callback(void*, void* context, void*) noexcept
{
auto that = reinterpret_cast<timespan_awaiter*>(context);
that->m_handle();
}
struct timer_traits
{
using type = impl::ptp_timer;
static void close(type value) noexcept
{
WINRT_IMPL_CloseThreadpoolTimer(value);
}
static constexpr type invalid() noexcept
{
return nullptr;
}
};
enum class state { idle, pending, canceled };
handle_type<timer_traits> m_timer;
Windows::Foundation::TimeSpan m_duration;
impl::coroutine_handle<> m_handle;
std::atomic<state> m_state{ state::idle };
};
struct signal_awaiter : cancellable_awaiter<signal_awaiter>
{
signal_awaiter(void* handle, Windows::Foundation::TimeSpan timeout) noexcept :
m_timeout(timeout),
m_handle(handle)
{}
#if defined(__GNUC__) && !defined(__clang__)
// HACK: GCC seems to require a move when calling operator co_await
// on the return value of resume_on_signal.
// This might be related to upstream bug:
// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=99575
signal_awaiter(signal_awaiter &&other) noexcept :
m_wait{std::move(other.m_wait)},
m_timeout{std::move(other.m_timeout)},
m_handle{std::move(other.m_handle)},
m_result{std::move(other.m_result)},
m_resume{std::move(other.m_resume)},
m_state{other.m_state.load()}
{}
#endif
void enable_cancellation(cancellable_promise* promise)
{
promise->set_canceller([](void* context)
{
auto that = static_cast<signal_awaiter*>(context);
if (that->m_state.exchange(state::canceled, std::memory_order_acquire) == state::pending)
{
that->fire_immediately();
}
}, this);
}
bool await_ready() const noexcept
{
return WINRT_IMPL_WaitForSingleObject(m_handle, 0) == 0;
}
template <typename T>
void await_suspend(impl::coroutine_handle<T> resume)
{
set_cancellable_promise_from_handle(resume);
m_resume = resume;
create_threadpool_wait();
}
bool await_resume()
{
if (m_state.exchange(state::idle, std::memory_order_relaxed) == state::canceled)
{
throw hresult_canceled();
}
return m_result == 0;
}
private:
void create_threadpool_wait()
{
m_wait.attach(check_pointer(WINRT_IMPL_CreateThreadpoolWait(callback, this, nullptr)));
int64_t relative_count = -m_timeout.count();
int64_t* file_time = relative_count != 0 ? &relative_count : nullptr;
WINRT_IMPL_SetThreadpoolWait(m_wait.get(), m_handle, file_time);
state expected = state::idle;
if (!m_state.compare_exchange_strong(expected, state::pending, std::memory_order_release))
{
fire_immediately();
}
}
void fire_immediately() noexcept
{
if (WINRT_IMPL_SetThreadpoolWaitEx(m_wait.get(), nullptr, nullptr, nullptr))
{
int64_t now = 0;
WINRT_IMPL_SetThreadpoolWait(m_wait.get(), WINRT_IMPL_GetCurrentProcess(), &now);
}
}
static void __stdcall callback(void*, void* context, void*, uint32_t result) noexcept
{
auto that = static_cast<signal_awaiter*>(context);
that->m_result = result;
that->m_resume();
}
struct wait_traits
{
using type = impl::ptp_wait;
static void close(type value) noexcept
{
WINRT_IMPL_CloseThreadpoolWait(value);
}
static constexpr type invalid() noexcept
{
return nullptr;
}
};
enum class state { idle, pending, canceled };
handle_type<wait_traits> m_wait;
Windows::Foundation::TimeSpan m_timeout;
void* m_handle;
uint32_t m_result{};
impl::coroutine_handle<> m_resume{ nullptr };
std::atomic<state> m_state{ state::idle };
};
}
WINRT_EXPORT namespace winrt
{
#ifdef WINRT_IMPL_COROUTINES
inline impl::apartment_awaiter operator co_await(apartment_context const& context)
{
return{ context };
}
#endif
[[nodiscard]] inline impl::timespan_awaiter resume_after(Windows::Foundation::TimeSpan duration) noexcept
{
return impl::timespan_awaiter{ duration };
}
#ifdef WINRT_IMPL_COROUTINES
inline impl::timespan_awaiter operator co_await(Windows::Foundation::TimeSpan duration)
{
return resume_after(duration);
}
#endif
[[nodiscard]] inline impl::signal_awaiter resume_on_signal(void* handle, Windows::Foundation::TimeSpan timeout = {}) noexcept
{
return impl::signal_awaiter{ handle, timeout };
}
struct thread_pool
{
thread_pool() :
m_pool(check_pointer(WINRT_IMPL_CreateThreadpool(nullptr)))
{
m_environment.Pool = m_pool.get();
}
void thread_limits(uint32_t const high, uint32_t const low)
{
WINRT_IMPL_SetThreadpoolThreadMaximum(m_pool.get(), high);
check_bool(WINRT_IMPL_SetThreadpoolThreadMinimum(m_pool.get(), low));
}
bool await_ready() const noexcept
{
return false;
}
void await_resume() const noexcept
{
}
void await_suspend(impl::coroutine_handle<> handle)
{
if (!WINRT_IMPL_TrySubmitThreadpoolCallback(callback, handle.address(), &m_environment))
{
throw_last_error();
}
}
private:
static void __stdcall callback(void*, void* context) noexcept
{
impl::coroutine_handle<>::from_address(context)();
}
struct pool_traits
{
using type = impl::ptp_pool;
static void close(type value) noexcept
{
WINRT_IMPL_CloseThreadpool(value);
}
static constexpr type invalid() noexcept
{
return nullptr;
}
};
struct environment // TP_CALLBACK_ENVIRON
{
uint32_t Version{ 3 };
void* Pool{};
void* CleanupGroup{};
void* CleanupGroupCancelCallback{};
void* RaceDll{};
void* ActivationContext{};
void* FinalizationCallback{};
union
{
uint32_t Flags{};
struct
{
uint32_t LongFunction : 1;
uint32_t Persistent : 1;
uint32_t Private : 30;
} s;
} u;
int32_t CallbackPriority{ 1 };
uint32_t Size{ sizeof(environment) };
};
handle_type<pool_traits> m_pool;
environment m_environment;
};
struct fire_and_forget {};
}
#ifdef __cpp_lib_coroutine
namespace std
#else
namespace std::experimental
#endif
{
template <typename... Args>
struct coroutine_traits<winrt::fire_and_forget, Args...>
{
struct promise_type
{
winrt::fire_and_forget get_return_object() const noexcept
{
return{};
}
void return_void() const noexcept
{
}
suspend_never initial_suspend() const noexcept
{
return{};
}
suspend_never final_suspend() const noexcept
{
return{};
}
void unhandled_exception() const noexcept
{
winrt::terminate();
}
};
};
}