librf

switch_scheduler.h
1 #pragma once
2
3 namespace resumef
4 {
8 struct switch_scheduler_awaitor
9 {
10 using value_type = void;
11 using state_type = state_t<value_type>;
12 using promise_type = promise_t<value_type>;
13 using lock_type = typename state_type::lock_type;
14
15 switch_scheduler_awaitor(scheduler_t* sch)
16 :_scheduler(sch) {}
17 switch_scheduler_awaitor(const switch_scheduler_awaitor&) = default;
18 switch_scheduler_awaitor(switch_scheduler_awaitor&&) = default;
19
20 switch_scheduler_awaitor& operator = (const switch_scheduler_awaitor&) = default;
21 switch_scheduler_awaitor& operator = (switch_scheduler_awaitor&&) = default;
22
23 bool await_ready() noexcept
24 {
25 return false;
26 }
27
28 template<class _PromiseT, typename = std::enable_if_t<traits::is_promise_v<_PromiseT>>>
29 bool await_suspend(coroutine_handle<_PromiseT> handler)
30 {
31 _PromiseT& promise = handler.promise();
32 auto* sptr = promise.get_state();
33 if (sptr->switch_scheduler_await_suspend(_scheduler))
34 {
35 counted_ptr<state_t<void>> _state = state_future_t::_Alloc_state<state_type>(true);
36 _state->set_value();
37 _state->future_await_suspend(handler);
38
39 return true;
40 }
41 return false;
42 }
43
44 void await_resume() noexcept
45 {
46 }
47
48 private:
49 scheduler_t* _scheduler;
50 #ifdef DOXYGEN_SKIP_PROPERTY
51 public:
61 static switch_scheduler_awaitor via(scheduler_t& sch) noexcept;
62
72 static switch_scheduler_awaitor via(scheduler_t* sch) noexcept;
73 #endif //DOXYGEN_SKIP_PROPERTY
74 };
75
76 //由于跟when_all/when_any混用的时候，在clang上编译失败：
77 //clang把scheduler_t判断成一个is_awaitable，且放弃选择when_all/any(scheduler_t& sch, ...)版本
78 //故放弃这种用法
79 //inline switch_scheduler_awaitor operator co_await(scheduler_t& sch) noexcept
80 //{
81 // return { &sch };
82 //}
83
91 inline switch_scheduler_awaitor via(scheduler_t& sch) noexcept
92 {
93 return { &sch };
94 }
95
100 inline switch_scheduler_awaitor via(scheduler_t* sch) noexcept
101 {
102 return { sch };
103 }
104
105 }
resumef::scheduler_t
协程调度器。
Definition: scheduler.h:10
resumef::counted_ptr
专用与state的智能计数指针，通过管理state内嵌的引用计数来管理state的生存期。
Definition: counted_ptr.h:9
resumef::spinlock
一个自旋锁实现。
Definition: spinlock.h:14
resumef::switch_scheduler_awaitor::via
static switch_scheduler_awaitor via(scheduler_t &sch) noexcept
将本协程切换到指定调度器上运行。
resumef::state_t
专用于future_t<>的state类。
Definition: state.h:217
resumef::switch_scheduler_awaitor
切换协程的可等待对象。
Definition: switch_scheduler.h:8