-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathscheduler.cpp
2524 lines (2140 loc) · 82.6 KB
/
scheduler.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
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
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* This file is part of Peredvizhnikov Engine
* Copyright (C) 2023 Eduard Permyakov
*
* Peredvizhnikov Engine is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Peredvizhnikov Engine is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
export module sync:scheduler;
export import <coroutine>;
export import shared_ptr;
import :worker_pool;
import :io_pool;
import concurrency;
import logger;
import platform;
import lockfree_queue;
import lockfree_list;
import lockfree_iterable_list;
import lockfree_sequenced_queue;
import event;
import meta;
import assert;
import atomic_work;
import tls;
import <array>;
import <queue>;
import <cstdint>;
import <thread>;
import <memory>;
import <type_traits>;
import <optional>;
import <bitset>;
import <unordered_set>;
import <stack>;
import <any>;
import <ranges>;
template <typename T, typename... Args>
struct std::coroutine_traits<pe::shared_ptr<T>, Args...>
{
using promise_type = typename T::promise_type;
};
namespace pe{
/*
* Forward declarations
*/
export using ::pe::Affinity;
export using ::pe::Priority;
export using tid_t = uint32_t;
export class Scheduler;
export
template <typename ReturnType, typename Derived, typename... Args>
class Task;
export
template <typename ReturnType, typename TaskType>
struct TaskPromise;
template <std::integral T>
inline uint16_t u16(T val)
{
return static_cast<uint16_t>(val);
}
template <std::integral T>
inline uint8_t u8(T val)
{
return static_cast<uint8_t>(val);
}
/*****************************************************************************/
/* TASK STATE */
/*****************************************************************************/
enum class TaskState : uint8_t
{
eSuspended,
eEventBlocked,
eYieldBlocked,
eRunning,
eZombie,
eJoined,
eSendBlocked,
eReceiveBlocked,
};
/*****************************************************************************/
/* TASK CREATE MODE */
/*****************************************************************************/
export
enum class CreateMode : uint32_t
{
eLaunchAsync,
eLaunchSync,
eSuspend
};
/*****************************************************************************/
/* VOID TYPE */
/*****************************************************************************/
/*
* Empty type to be used as a void yield value
*/
export struct VoidType {};
export constexpr VoidType Void = VoidType{};
/*****************************************************************************/
/* MESSAGE */
/*****************************************************************************/
export
struct Message
{
pe::weak_ptr<TaskBase> m_sender;
uint64_t m_header;
std::any m_payload;
};
/*****************************************************************************/
/* TASK INITIAL AWAITABLE */
/*****************************************************************************/
/*
* Starts or suspends the coroutine, depending on the creation mode.
*/
struct TaskInitialAwaitable
{
private:
Scheduler& m_scheduler;
Schedulable m_schedulable;
CreateMode m_mode;
public:
TaskInitialAwaitable(Scheduler& scheduler, Schedulable schedulable, CreateMode mode)
: m_scheduler{scheduler}
, m_schedulable{schedulable}
, m_mode{mode}
{}
bool await_ready() const noexcept;
template <typename PromiseType>
void await_suspend(std::coroutine_handle<PromiseType>) const noexcept;
void await_resume() const noexcept {}
};
/*****************************************************************************/
/* TASK AWAITABLE */
/*****************************************************************************/
/*
* A TaskAwaitable / TaskPromise pair implement the mechanics
* of awaiting on a yield from a task, be that from a co_yield
* or a co_return.
*/
template <typename ReturnType, typename PromiseType>
struct TaskAwaitable
{
protected:
template <typename OtherReturnType, typename OtherTaskType>
using handle_type =
std::coroutine_handle<TaskPromise<OtherReturnType, OtherTaskType>>;
Scheduler& m_scheduler;
SharedCoroutinePtr<PromiseType> m_coro;
public:
TaskAwaitable(Scheduler& scheduler, SharedCoroutinePtr<PromiseType> coro);
bool await_ready();
template <typename OtherReturnType, typename OtherTaskType>
bool await_suspend(handle_type<OtherReturnType, OtherTaskType> awaiter_handle);
template <typename U = ReturnType>
requires (!std::is_void_v<U>)
U&& await_resume();
template <typename U = ReturnType>
requires (std::is_void_v<U>)
U await_resume();
Schedulable Schedulable()
{
return m_coro->Promise().Schedulable();
}
};
/*****************************************************************************/
/* TASK TERMINATE AWAITABLE */
/*****************************************************************************/
template <typename ReturnType, typename PromiseType>
struct TaskTerminateAwaitable : public TaskAwaitable<ReturnType, PromiseType>
{
using TaskAwaitable<ReturnType, PromiseType>::TaskAwaitable;
template <typename U = ReturnType>
requires (!std::is_void_v<U>)
U await_resume();
template <typename U = ReturnType>
requires (std::is_void_v<U>)
U await_resume();
};
/*****************************************************************************/
/* EVENT AWAITABLE */
/*****************************************************************************/
template <EventType Event>
struct EventAwaitable : public pe::enable_shared_from_this<EventAwaitable<Event>>
{
private:
Scheduler& m_scheduler;
Schedulable m_awaiter;
pe::weak_ptr<void> m_awaiter_task;
tid_t m_awaiter_tid;
std::optional<event_arg_t<Event>> m_arg;
void (*m_advance_state)(pe::weak_ptr<void>, TaskState);
bool (*m_is_notified)(pe::weak_ptr<void>, uint8_t);
std::optional<event_arg_t<Event>> (*m_next_event)(pe::weak_ptr<void>);
class EventAwaitableCreateToken
{
EventAwaitableCreateToken() = default;
friend struct EventAwaitable;
};
public:
EventAwaitable(EventAwaitable const&) = delete;
EventAwaitable& operator=(EventAwaitable const&) = delete;
template <typename TaskType>
EventAwaitable(EventAwaitableCreateToken token, TaskType& task)
: m_scheduler{task.Scheduler()}
, m_awaiter{task.Schedulable()}
, m_awaiter_task{task.shared_from_this()}
, m_awaiter_tid{task.TID()}
, m_arg{}
, m_advance_state(+[](pe::weak_ptr<void> ptr, TaskState state){
auto task = pe::static_pointer_cast<TaskType>(ptr.lock());
if(!task)
return;
auto old = task->m_coro->Promise().PollState();
std::size_t event = static_cast<std::size_t>(Event);
while(true) {
if(task->m_coro->Promise().TryAdvanceState(old,
{state, old.m_message_seqnum,
old.m_unblock_counter, old.m_notify_counter,
old.m_event_seqnums,
u16(old.m_awaiting_event_mask & ~(0b1 << event)),
old.m_awaiter})) {
break;
}
}
})
, m_is_notified(+[](pe::weak_ptr<void> ptr, uint8_t counter){
auto task = pe::static_pointer_cast<TaskType>(ptr.lock());
if(!task)
return true;
auto old = task->m_coro->Promise().PollState();
uint8_t next_counter = counter + 1;
if(old.m_notify_counter == counter)
return false;
if(old.m_notify_counter == next_counter)
return true;
/* It's a 'lagging' call */
return true;
})
, m_next_event(+[](pe::weak_ptr<void> ptr){
auto task = pe::static_pointer_cast<TaskType>(ptr.lock());
if(!task)
return std::optional<event_arg_t<Event>>{};
return task->template next_event<Event>();
})
{}
template <typename TaskType>
static pe::shared_ptr<EventAwaitable> Create(TaskType& task)
{
return pe::make_shared<EventAwaitable>(EventAwaitableCreateToken{}, task);
}
void SetArg(event_arg_t<Event> arg)
{
m_arg = arg;
}
bool await_ready()
{
auto event = m_next_event(m_awaiter_task);
if(!event.has_value())
return false;
m_arg = event.value();
return true;
}
template <typename PromiseType>
bool await_suspend(std::coroutine_handle<PromiseType> awaiter_handle) noexcept;
event_arg_t<Event> await_resume()
{
return m_arg.value();
}
void AdvanceState(TaskState state)
{
m_advance_state(m_awaiter_task, state);
}
tid_t AwaiterTID() const
{
return m_awaiter_tid;
}
std::string_view AwaiterName() const;
Schedulable Awaiter(uint64_t seqnum) const
{
return m_awaiter;
}
bool IsNotified(uint8_t counter) const
{
return m_is_notified(m_awaiter_task, counter);
}
};
/*****************************************************************************/
/* YIELD AWAITABLE */
/*****************************************************************************/
struct YieldAwaitable
{
Scheduler& m_scheduler;
Schedulable m_schedulable;
bool await_ready() const noexcept { return false; }
void await_suspend(std::coroutine_handle<>) const noexcept;
void await_resume() const noexcept {}
};
/*****************************************************************************/
/* SEND AWAITABLE */
/*****************************************************************************/
struct SendAwaitable
{
private:
Scheduler& m_scheduler;
Schedulable m_awaiter;
pe::weak_ptr<void> m_awaiter_task;
pe::weak_ptr<void> m_receiver;
Message m_message;
Message m_response;
void (*m_send_message)(pe::shared_ptr<void>, Scheduler&, const Message&);
public:
template <typename SenderType, typename ReceiverType>
SendAwaitable(Scheduler& scheduler, Schedulable awaiter,
pe::shared_ptr<ReceiverType> receiver, pe::shared_ptr<SenderType>, Message message);
bool await_ready() noexcept;
template <typename PromiseType>
bool await_suspend(std::coroutine_handle<PromiseType> awaiter) noexcept
{
auto receiver = m_receiver.lock();
if(!receiver) {
m_response = Message{};
return false;
}
m_send_message(receiver, m_scheduler, m_message);
return true;
}
Message await_resume() const noexcept
{
return m_response;
}
};
/*****************************************************************************/
/* RECV AWAITABLE */
/*****************************************************************************/
struct RecvAwaitable
{
private:
Schedulable m_awaiter;
pe::weak_ptr<void> m_awaiter_task;
Message m_message;
std::optional<Message> (*m_try_pop_message)(pe::shared_ptr<void>);
std::optional<Message> (*m_pop_message_or_block)(pe::shared_ptr<void>);
public:
template <typename AwaiterType>
RecvAwaitable(Schedulable awaiter, pe::shared_ptr<AwaiterType> task)
: m_awaiter{awaiter}
, m_awaiter_task{task}
, m_message{}
, m_try_pop_message{+[](pe::shared_ptr<void> awaiter){
auto task = pe::static_pointer_cast<AwaiterType>(awaiter);
return task->PollMessage();
}}
, m_pop_message_or_block{+[](pe::shared_ptr<void> awaiter){
struct DequeueState
{
AwaiterType::promise_type::ControlBlock m_expected;
AwaiterType::promise_type& m_promise;
};
using queue_type = AwaiterType::message_queue_type;
auto task = pe::static_pointer_cast<AwaiterType>(awaiter);
auto& promise = task->m_coro->Promise();
auto state = promise.PollState();
auto dequeue_state = pe::make_shared<DequeueState>(state,
task->m_coro->Promise());
std::optional<Message> message;
typename queue_type::ProcessingResult result;
uint64_t pseqnum;
auto processor = +[](const pe::shared_ptr<DequeueState> state,
uint64_t seqnum, Message message) {
auto advanced = +[](uint8_t a, uint8_t b) -> bool {
return (static_cast<int8_t>((b) - (a)) < 0);
};
auto expected = state->m_expected;
while(true) {
typename AwaiterType::promise_type::ControlBlock newstate{
expected.m_state,
u8(seqnum),
expected.m_unblock_counter,
expected.m_notify_counter,
expected.m_event_seqnums,
expected.m_awaiting_event_mask,
expected.m_awaiter
};
if(advanced(expected.m_message_seqnum, seqnum))
break;
if(state->m_promise.TryAdvanceState(expected, newstate))
break;
}
return queue_type::ProcessingResult::eDelete;
};
auto fallback = +[](const pe::shared_ptr<DequeueState> state, uint64_t seqnum) {
auto advanced = +[](uint8_t a, uint8_t b) -> bool {
return (static_cast<int8_t>((b) - (a)) < 0);
};
auto expected = state->m_expected;
while(true) {
typename AwaiterType::promise_type::ControlBlock newstate{
TaskState::eSendBlocked,
expected.m_message_seqnum,
expected.m_unblock_counter,
expected.m_notify_counter,
expected.m_event_seqnums,
expected.m_awaiting_event_mask,
expected.m_awaiter
};
if(advanced(expected.m_message_seqnum, seqnum))
break;
if(state->m_promise.TryAdvanceState(expected, newstate))
break;
if(expected.m_state == TaskState::eSendBlocked)
break;
}
};
std::tie(message, result, pseqnum) = task->m_message_queue.ProcessHead(processor,
fallback, dequeue_state);
return message;
}}
{}
bool await_ready() noexcept
{
auto awaiter = m_awaiter_task.lock();
pe::assert(awaiter != nullptr);
if(auto message = m_try_pop_message(awaiter)) {
m_message = message.value();
return true;
}
return false;
}
template <typename PromiseType>
bool await_suspend(std::coroutine_handle<PromiseType> awaiter) noexcept
{
auto receiver = m_awaiter_task.lock();
pe::assert(receiver != nullptr);
if(auto message = m_pop_message_or_block(receiver)) {
m_message = message.value();
return false;
}
return true;
}
Message await_resume() const noexcept
{
auto awaiter = m_awaiter_task.lock();
pe::assert(awaiter != nullptr);
auto uninitialized = [](pe::weak_ptr<void> const& ptr){
using wp = pe::weak_ptr<void>;
return !ptr.owner_before(wp{}) && !wp{}.owner_before(ptr);
};
if(uninitialized(m_message.m_sender)) {
return m_try_pop_message(awaiter).value();
}
return m_message;
}
void SetMessage(Message message)
{
m_message = message;
}
};
/*****************************************************************************/
/* TASK PROMISE */
/*****************************************************************************/
/*
* The compiler doesn't allow these two declarations to appear
* together in one promise_type class, so we must conditonally
* inherit one of them.
*/
template <typename ReturnType, typename Derived>
struct TaskValuePromiseBase
{
template <std::convertible_to<ReturnType> From>
void return_value(From&& value)
{
static_cast<Derived*>(this)->m_value = std::forward<From>(value);
}
};
template <typename Derived>
struct TaskVoidPromiseBase
{
void return_void() {}
};
export
template <typename ReturnType, typename TaskType>
struct TaskPromise : public std::conditional_t<
std::is_void_v<ReturnType>,
TaskVoidPromiseBase<TaskPromise<ReturnType, TaskType>>,
TaskValuePromiseBase<ReturnType, TaskPromise<ReturnType, TaskType>>
>
{
public:
struct alignas(16) ControlBlock
{
TaskState m_state;
uint8_t m_message_seqnum;
uint8_t m_unblock_counter;
uint8_t m_notify_counter;
uint16_t m_event_seqnums;
uint16_t m_awaiting_event_mask;
const Schedulable *m_awaiter;
bool operator==(const ControlBlock& rhs) const noexcept
{
return m_state == rhs.m_state
&& m_message_seqnum == rhs.m_message_seqnum
&& m_unblock_counter == rhs.m_unblock_counter
&& m_notify_counter == rhs.m_notify_counter
&& m_event_seqnums == rhs.m_event_seqnums
&& m_awaiting_event_mask == rhs.m_awaiting_event_mask
&& m_awaiter == rhs.m_awaiter;
}
};
private:
friend struct TaskVoidPromiseBase<TaskPromise<ReturnType, TaskType>>;
friend struct TaskValuePromiseBase<ReturnType, TaskPromise<ReturnType, TaskType>>;
template <typename OtherTaskType>
friend struct task_traits;
using return_type = ReturnType;
using promise_type = TaskPromise<ReturnType, TaskType>;
using coroutine_type = Coroutine<promise_type>;
using value_type = std::conditional_t<
std::is_void_v<ReturnType>,
std::monostate,
ReturnType
>;
using AtomicControlBlock = DoubleQuadWordAtomic<ControlBlock>;
AtomicControlBlock m_state;
value_type m_value;
std::exception_ptr m_exception;
std::vector<std::string> m_exception_backtrace;
Schedulable m_awaiter;
/* Keep around a shared pointer to the Task instance which has
* the 'Run' coroutine method. This way we will prevent
* destruction of that instance until the 'Run' method runs to
* completion and the promise final_suspend method is invoked
* or the task is terminated at the current suspend point,
* allowing us to safely use the 'this' pointer in the method
* without worrying about the instance lifetime.
*/
pe::shared_ptr<TaskType> m_task;
pe::shared_ptr<TaskType> release_task()
{
auto ret = m_task;
m_task.reset();
return ret;
}
public:
using task_type = TaskType;
bool TryAdvanceState(ControlBlock& expected, ControlBlock next)
{
AnnotateHappensBefore(__FILE__, __LINE__, &m_state);
return m_state.CompareExchange(expected, next,
std::memory_order_release, std::memory_order_relaxed);
}
pe::shared_ptr<TaskType> get_return_object()
{
return {m_task};
}
void unhandled_exception()
{
m_exception = std::current_exception();
m_exception_backtrace = Backtrace();
}
TaskInitialAwaitable initial_suspend()
{
return {
m_task->Scheduler(),
Schedulable(),
m_task->GetCreateMode()
};
}
YieldAwaitable final_suspend() noexcept
{
auto state = PollState();
bool done = false;
auto task = release_task();
while(!done) {
switch(state.m_state) {
case TaskState::eRunning:
if(state.m_awaiter) {
if(TryAdvanceState(state,
{TaskState::eJoined, state.m_message_seqnum,
state.m_unblock_counter, state.m_notify_counter,
state.m_event_seqnums, state.m_awaiting_event_mask, nullptr})) {
done = true;
break;
}
}else{
if(TryAdvanceState(state,
{TaskState::eZombie, state.m_message_seqnum,
state.m_unblock_counter, state.m_notify_counter,
state.m_event_seqnums, state.m_awaiting_event_mask, nullptr})) {
done = true;
break;
}
}
break;
default:
pe::assert(0);
}
}
/* We have an awaiter */
if(state.m_awaiter) {
AnnotateHappensAfter(__FILE__, __LINE__, &m_state);
auto ret = YieldAwaitable{task->Scheduler(), *state.m_awaiter};
m_awaiter = {};
return ret;
}
/* We terminated due to an unhandled exception but don't
* have an awaiter. Propagate the exception to the main thread.
*/
if(m_exception) {
TaskException exc(std::string{task->Name()}, task->TID(),
m_exception_backtrace, m_exception);
task->Scheduler().template notify_event<EventType::eUnhandledTaskException>(exc);
}
return {task->Scheduler(), {}};
}
template <typename OtherTaskType>
typename OtherTaskType::awaitable_type
await_transform(pe::shared_ptr<OtherTaskType>&& value)
{
return {value->m_scheduler, value->m_coro};
}
template <typename OtherTaskType>
typename OtherTaskType::awaitable_type
await_transform(pe::shared_ptr<OtherTaskType>& value)
{
return {value->m_scheduler, value->m_coro};
}
template <EventType Event>
EventAwaitable<Event>&
await_transform(pe::shared_ptr<EventAwaitable<Event>>&& value)
{
return *value;
}
template <typename Awaitable>
Awaitable await_transform(Awaitable&& value)
{
return value;
}
template <typename U = ReturnType, std::convertible_to<U> From>
requires (!std::is_void_v<U>)
YieldAwaitable yield_value(From&& value)
{
m_value = std::forward<From>(value);
auto state = PollState();
bool done = false;
while(!done) {
switch(state.m_state) {
case TaskState::eRunning:
if(state.m_awaiter) {
if(TryAdvanceState(state,
{TaskState::eSuspended, state.m_message_seqnum,
state.m_unblock_counter, state.m_notify_counter,
state.m_event_seqnums, state.m_awaiting_event_mask, nullptr})) {
done = true;
break;
}
}else{
if(TryAdvanceState(state,
{TaskState::eYieldBlocked, state.m_message_seqnum,
state.m_unblock_counter, state.m_notify_counter,
state.m_event_seqnums, state.m_awaiting_event_mask, nullptr})) {
done = true;
break;
}
}
break;
default:
pe::assert(0);
}
}
/* We have an awaiter */
if(state.m_awaiter) {
AnnotateHappensAfter(__FILE__, __LINE__, &m_state);
auto ret = YieldAwaitable{m_task->Scheduler(), *state.m_awaiter};
m_awaiter = {};
return ret;
}
/* We have become yield-blocked */
return {m_task->m_scheduler, {}};
}
template <typename U = ReturnType>
requires (std::is_void_v<U>)
YieldAwaitable yield_value(const VoidType&)
{
auto state = PollState();
bool done = false;
while(!done) {
switch(state.m_state) {
case TaskState::eRunning:
if(state.m_awaiter) {
if(TryAdvanceState(state,
{TaskState::eSuspended, state.m_message_seqnum,
state.m_unblock_counter, state.m_notify_counter,
state.m_event_seqnums, state.m_awaiting_event_mask, nullptr})) {
done = true;
break;
}
}else{
if(TryAdvanceState(state,
{TaskState::eYieldBlocked, state.m_message_seqnum,
state.m_unblock_counter, state.m_notify_counter,
state.m_event_seqnums, state.m_awaiting_event_mask, nullptr})) {
done = true;
break;
}
}
break;
default:
pe::assert(0);
}
}
/* We have an awaiter */
if(state.m_awaiter) {
AnnotateHappensAfter(__FILE__, __LINE__, &m_state);
auto ret = YieldAwaitable{m_task->m_scheduler, *state.m_awaiter};
m_awaiter = {};
return ret;
}
/* We have become yield-blocked */
return {m_task->m_scheduler, {}};
}
template <typename... Args>
TaskPromise(TaskType& task, Args&... args)
: m_state{{(task.GetCreateMode() == CreateMode::eSuspend) ? TaskState::eSuspended : TaskState::eRunning,
0, 0, 0, 0, 0, nullptr}}
, m_value{}
, m_exception{}
, m_awaiter{}
, m_task{task.shared_from_this()}
{
task.m_coro = pe::make_shared<Coroutine<promise_type>>(
std::coroutine_handle<promise_type>::from_promise(*this),
std::string{task.Name()}
);
}
const Schedulable Schedulable() const
{
return m_task->Schedulable();
}
Scheduler& Scheduler() const
{
return m_task->Scheduler();
}
struct Schedulable *SetAwaiter(struct Schedulable schedulable)
{
m_awaiter = schedulable;
return &m_awaiter;
}
pe::shared_ptr<TaskType> Task() const
{
return m_task;
}
ControlBlock PollState() const
{
return m_state.Load(std::memory_order_acquire);
}
/* This is only called when the task is already suspended */
void Terminate()
{
m_task.reset();
m_awaiter = {};
m_state.Store({TaskState::eJoined, 0, 0, 0, 0, 0, nullptr},
std::memory_order_release);
}
template <typename U = ReturnType>
requires (!std::is_void_v<U>)
U&& Value()
{
return std::move(m_value);
}
const std::exception_ptr& Exception() const
{
return m_exception;
}
};
/*****************************************************************************/
/* TASK TRAITS */
/*****************************************************************************/
export
template <typename Task>
struct task_traits
{
using return_type = typename Task::promise_type::return_type;
};
/*****************************************************************************/
/* TASK */
/*****************************************************************************/
[[maybe_unused]] inline std::atomic_uint32_t s_next_tid{0};
export
class TaskBase
{
private:
tid_t m_tid;
std::unique_ptr<char, void(*)(void*)> m_name;
pe::shared_ptr<TaskBase> m_parent;
std::vector<pe::weak_ptr<TaskBase>> m_children;
std::atomic<Message*> m_response;
void (*m_release)(TaskBase*);
void (*m_unblock)(pe::shared_ptr<TaskBase>);
protected:
template <typename Derived>
TaskBase(std::in_place_type_t<Derived>)
: m_tid{s_next_tid.fetch_add(1, std::memory_order_relaxed)}
, m_name{Demangle(std::string{typeid(Derived).name()})}
, m_parent{}
, m_children{}
, m_response{}
, m_release{+[](TaskBase *base){
auto *task = static_cast<Derived*>(base);
task->release();
}}
, m_unblock{+[](pe::shared_ptr<TaskBase> base){
auto task = pe::static_pointer_cast<Derived>(base);
task->m_scheduler.enqueue_task(task->Schedulable());
}}
{}
public:
virtual ~TaskBase() = default;
tid_t TID() const
{
return m_tid;
}
std::string_view Name() const
{
if(!m_name.get())
return {""};
return {m_name.get()};
}
void SetParent(pe::shared_ptr<TaskBase> parent)
{
m_parent = parent;
}
void AddChild(pe::shared_ptr<TaskBase> child)
{
m_children.push_back(child);
}
const std::vector<pe::weak_ptr<TaskBase>>& GetChildren() const
{
return m_children;
}
void Release()