Debian Codegraph @

examples/co-async.hpp

raw symbols SCIP
1 #pragma once
2
3 #include <gi/gi.hpp>
4
5 #include <coroutine>
6 #include <future>
7
8 #ifdef CO_DEBUG
9 #include <iostream>
10 static auto &dout = std::cerr;
11 #else
12 #include <sstream>
13 static std::ostringstream dout;
14 #endif
15
16 template<typename T, typename SELF>
17 struct holder
18 {
19 void return_value(T &&v)
20 {
21 dout << "return value " << std::endl;
22 auto self = (SELF *)this;
23 self->set_value(std::move(v));
24 }
25 };
26
27 template<typename SELF>
28 struct holder<void, SELF>
29 {
30 void return_void()
31 {
32 auto self = (SELF *)this;
33 self->set_value();
34 }
35 };
36
37 template<typename RESULT>
38 class co_promise : public std::promise<RESULT>
39 {
40 using self_type = co_promise;
41 // some protection for a coroutine_handle<>
42 // so we do not try to access one that may be invalid/dangling
43
44 // `this` is alive as long as the co_await expression is alive (suspended)
45 // so this can be passed in raw form for the lifetime of `waiter` below
46 // conversely, as long as a `waiter` is alive, it tracks a refcount in count_
47 // so, if the count is positive, the handle of the suspended coroutine is ok
48 // if not, the objects in the expression of the suspended coroutine could
49 // no longer be around either
50
51 int count_ = 0;
52 std::future<RESULT> result_;
53 std::coroutine_handle<> waiter_;
54
55 public:
56 struct waiter
57 {
58 self_type *target_;
59
60 waiter(self_type *t) : target_(t) { ++target_->count_; }
61 ~waiter() { --target_->count_; }
62
63 self_type &w() const { return *target_; }
64
65 bool await_ready() const
66 {
67 return w().result_.wait_for(std::chrono::seconds(0)) ==
68 std::future_status::ready;
69 }
70 void await_suspend(std::coroutine_handle<> handle)
71 {
72 assert(!w().waiter_);
73 w().waiter_ = handle;
74 }
75 RESULT await_resume()
76 {
77 // should have value now, or may hang otherwise
78 assert(await_ready());
79 return w().result_.get();
80 }
81 };
82
83 co_promise() { result_ = this->get_future(); }
84
85 void reset() { *this = self_type(); }
86
87 waiter operator co_await() { return waiter{this}; }
88
89 bool resume()
90 {
91 auto w = coro();
92 // waiter takes care of itself again
93 waiter_ = nullptr;
94 w.resume();
95 return bool(w);
96 }
97
98 std::coroutine_handle<> coro(bool check = true)
99 {
100 auto handle = waiter_;
101 return (count_ || !check) && handle ? handle : std::noop_coroutine();
102 }
103 };
104
105 // task represents an owning handle of a coroutine
106 // in particular, the task can be cancelled by mere destruction
107 // however, this is generally a bad idea (sort of equivalent to pthread_cancel),
108 // as such, some checks serve to check/discourage this (by default)
109 template<typename RESULT, bool CANCELLABLE = false>
110 class task
111 {
112 public:
113 struct promise_type;
114 std::coroutine_handle<promise_type> coro_;
115
116 public:
117 struct promise_type : public holder<RESULT, promise_type>
118 {
119 co_promise<RESULT> result_;
120 bool finish_{false};
121
122 auto get_return_object()
123 {
124 return task(std::coroutine_handle<promise_type>::from_promise(*this));
125 }
126 std::suspend_never initial_suspend() { return {}; }
127 class final_awaiter
128 {
129 bool ready_;
130
131 public:
132 final_awaiter(bool f) : ready_(f) {}
133 bool await_ready() const noexcept { return ready_; }
134 void await_resume() noexcept {}
135 std::coroutine_handle<> await_suspend(
136 std::coroutine_handle<promise_type> h) noexcept
137 {
138 dout << "final await_suspend " << std::endl;
139 // final_awaiter::await_suspend is called when the execution of the
140 // current coroutine (referred to by 'h') is about to finish.
141 // If the current coroutine was resumed by another coroutine via
142 // co_await, a handle to that coroutine has been stored in result_.
143 // Use that to refer to previous coroutine (as next to resume).
144 return h.promise().result_.coro();
145 }
146 };
147
148 final_awaiter final_suspend() noexcept { return {finish_}; }
149 void unhandled_exception()
150 {
151 result_.set_exception(std::current_exception());
152 }
153 // coroutine may not define both return_value and return_void
154 // so we bounce through a helper (super)class and method
155 template<typename... T>
156 void set_value(T &&...t)
157 {
158 static_assert(sizeof...(T) <= 1, "");
159 result_.set_value(std::forward<T>(t)...);
160 }
161 };
162
163 task(std::coroutine_handle<promise_type> h) : coro_(h) {}
164 task(task &&t) = delete;
165 ~task()
166 {
167 if (coro_) {
168 // notify in a hard way that a coroutine task is dropped mid-air
169 if (!CANCELLABLE && !coro_.done()) {
170 gi::detail::try_throw(std::runtime_error("coroutine cancelled"));
171 }
172 coro_.destroy();
173 }
174 }
175
176 // similar to thread's detach()
177 // the task is subsequently on its own (to cleanup)
178 void detach()
179 {
180 // only makes sense if no value is produced/expected
181 static_assert(std::is_same<void, RESULT>::value, "");
182 // release ownership
183 if (coro_) {
184 // may be done (in final suspend) already
185 // only needs to destroy upon resume, so do that here directly
186 if (coro_.done()) {
187 coro_.destroy();
188 } else {
189 // disable final suspend of final waiter above
190 coro_.promise().finish_ = true;
191 }
192 }
193 coro_ = nullptr;
194 }
195
196 auto operator co_await()
197 {
198 if (!coro_)
199 gi::detail::try_throw(std::invalid_argument("no coroutine"));
200 return coro_.promise().result_.operator co_await();
201 }
202 };