mrs_lib
Various reusable classes, functions and utilities for use in MRS projects
Loading...
Searching...
No Matches
task.hpp
1#ifndef MRS_LIB_CORO_TASK_HPP_
2#define MRS_LIB_CORO_TASK_HPP_
3
4#include <cassert>
5#include <concepts>
6#include <coroutine>
7#include <functional>
8#include <memory>
9#include <type_traits>
10#include <utility>
11
12#include "mrs_lib/coro/internal/attributes.hpp"
13#include "mrs_lib/coro/internal/continuation.hpp"
14#include "mrs_lib/coro/internal/result_storage.hpp"
15#include "mrs_lib/coro/internal/thread_local_continuation_scheduler.hpp"
16#include "mrs_lib/utility/scope_cleanup.hpp"
17
18// Note on ownership semantics:
19// Since we want to support cancellation at any point in the coroutine stacks,
20// each coroutine is owned by the object responsible for resuming it. If the
21// coroutine is running, it is responsible for it's own lifetime - it has to
22// either suspend and become continuation of some other task thus transferring
23// ownership or destruct itself once completed.
24
25namespace mrs_lib::coro
26{
27
28 template <typename T = void>
29 requires(std::same_as<T, std::remove_cvref_t<T>>)
30 class Task;
31
32 namespace internal
33 {
34
41 template <typename Derived>
43 {
49 class FinalAwaitable
50 {
51 public:
52 FinalAwaitable() = default;
53 ~FinalAwaitable() = default;
54 FinalAwaitable(const FinalAwaitable&) = delete;
55 FinalAwaitable& operator=(const FinalAwaitable&) = delete;
56 FinalAwaitable(FinalAwaitable&&) = delete;
57 FinalAwaitable& operator=(FinalAwaitable&&) = delete;
58
59 // Always suspend the ending task
60 bool await_ready() noexcept;
61
62 // SYMMETRIC TRANSFER IS BROKEN IN GCC and can result in stack
63 // overflow when many tasks complete synchronously.
64 // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=100897
65 // Because of this problem, the `await_suspend` uses the void signature
66 // and resumes the continuation on a thread-local scheduler as a workaround.
67 void await_suspend(std::coroutine_handle<Derived> task_handle) noexcept;
68
69 // This should be unreachable - ended task should not be resumed
70 void await_resume() noexcept;
71 };
72
73 public:
74 // The task is lazy and will only start when awaited
75 std::suspend_always initial_suspend();
76 // The coroutine will be suspended and the continuation will be resumed
77 FinalAwaitable final_suspend() noexcept;
78
79 void set_continuation(CancellableContinuation continuation);
80
81 CancellableContinuation release_continuation()
82 {
83 return std::exchange(continuation_, {});
84 }
85
86 [[nodiscard]] std::stop_token get_token() const
87 {
88 return continuation_.get_token();
89 }
90
91 private:
92 CancellableContinuation continuation_;
93 };
94
100 template <typename T>
101 class PromiseType : public BasePromiseType<PromiseType<T>>
102 {
103 public:
104 Task<T> get_return_object();
105
106 void return_value(T&& ret_val);
107
108 void unhandled_exception();
109
110 T get_value()
111 {
112 return std::move(result_).get_value();
113 }
114
115 private:
116 ResultStorage<T> result_;
117 };
118
124 template <>
125 class PromiseType<void> : public BasePromiseType<PromiseType<void>>
126 {
127 public:
128 Task<void> get_return_object();
129
130 void return_void();
131
132 void unhandled_exception();
133
134 void get_value()
135 {
136 if (exception_)
137 {
138 std::rethrow_exception(exception_);
139 }
140 }
141
142 private:
143 std::exception_ptr exception_;
144 };
145
146 template <typename T>
148 {
149 static CancellableContinuation release_continuation(std::coroutine_handle<PromiseType<T>> handle)
150 {
151 PromiseType<T>& promise = handle.promise();
152 return promise.release_continuation();
153 };
154
155 static std::stop_token get_token(std::coroutine_handle<PromiseType<T>> handle)
156 {
157 return handle.promise().get_token();
158 }
159 };
160
167 template <typename T>
168 class TaskAwaitable
169 {
170 using Promise = Task<T>::promise_type;
171
172 public:
173 bool await_ready()
174 {
175 return false;
176 }
177
178 // SYMMETRIC TRANSFER IS BROKEN IN GCC and can result in stack
179 // overflow when many tasks complete synchronously.
180 // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=100897
181 // Because of this problem, the `await_suspend` uses the void signature
182 // and resumes the continuation on a thread-local scheduler as a workaround.
183 template <typename CallerPromise>
184 void await_suspend(std::coroutine_handle<CallerPromise> continuation)
185 {
186 task_handle_.promise().set_continuation(CancellableContinuation(continuation));
187 schedule_coroutine_continuation(task_handle_);
188 }
189
190 T await_resume()
191 {
192 ScopeCleanup destroyer_cleanup([this] { this->task_handle_.destroy(); });
193 return this->task_handle_.promise().get_value();
194 }
195
196 ~TaskAwaitable() = default;
197 TaskAwaitable(const TaskAwaitable&) = delete;
198 TaskAwaitable& operator=(const TaskAwaitable&) = delete;
199 TaskAwaitable(TaskAwaitable&&) = delete;
200 TaskAwaitable& operator=(TaskAwaitable&&) = delete;
201
202 // This type should only be awaitable when directly returned from the
203 // co_await operator of Task. This prevents it from being awaitable when
204 // not returned from co_await operator.
205 void operator co_await() const = delete;
206
207 private:
208 TaskAwaitable(std::coroutine_handle<Promise> task_handle) : task_handle_(task_handle)
209 {
210 }
211
212 std::coroutine_handle<Promise> task_handle_;
213
214 friend class Task<T>;
215 };
216
217 } // namespace internal
218
227 template <typename T>
228 requires(std::same_as<T, std::remove_cvref_t<T>>)
229 class [[nodiscard("Task is lazy and does not run until `co_await`ed.")]] Task
230 {
231 public:
232 using promise_type = internal::PromiseType<T>;
233
234 ~Task()
235 {
236 if (coroutine_)
237 {
238 coroutine_.destroy();
239 }
240 }
241
242 Task(const Task&) = delete;
243 Task& operator=(const Task&) = delete;
244 Task(Task&&) = delete;
245 Task& operator=(Task&&) = delete;
246
247 friend internal::TaskAwaitable<T> operator co_await(Task task)
248 {
249 return internal::TaskAwaitable<T>(std::exchange(task.coroutine_, {}));
250 }
251
252 private:
253 explicit Task(std::coroutine_handle<promise_type> coroutine) : coroutine_(std::move(coroutine))
254 {
255 }
256
257 std::coroutine_handle<promise_type> coroutine_;
258
259 friend class internal::PromiseType<T>;
260 };
261
262} // namespace mrs_lib::coro
263
264namespace mrs_lib
265{
266 // Export mrs_lib::coro::Task directly into mrs_lib namespace since it is
267 // likely to be used often.
268 using coro::Task;
269
270} // namespace mrs_lib
271
272#ifndef MRS_LIB_CORO_TASK_IMPL_HPP_
273#include "mrs_lib/coro/task.impl.hpp" // IWYU pragma: export
274#endif
275
276#endif // MRS_LIB_CORO_TASK_HPP_
Utility class for running cleanup at the end of a scope.
Definition scope_cleanup.hpp:17
Task type for creating coroutines.
Definition task.hpp:230
Base class for the task's promise type.
Definition task.hpp:43
Owning coroutine handle supporting cancellation.
Definition continuation.hpp:54
std::stop_token get_token() const
Get stop token associated with the continuation.
Definition continuation.hpp:142
Promise type for non-void task.
Definition task.hpp:102
A variant-like class for storing the result of non-void task.
Definition result_storage.hpp:18
Awaitable used to co_await other tasks.
Definition task.hpp:169
All mrs_lib functions, classes, variables and definitions are contained in this namespace.
Definition attitude_converter.h:24
Type trait to obtain data necessary for creating CancellableContinuation.
Definition continuation.hpp:37