Condy v1.8
C++ Asynchronous System Call Layer for Linux
Loading...
Searching...
No Matches
task.hpp
Go to the documentation of this file.
1
7
8#pragma once
9
10#include "condy/coro.hpp"
12#include "condy/detail/task.hpp"
13#include "condy/runtime.hpp"
14#include <coroutine>
15#include <exception>
16#include <utility>
17
18namespace condy {
19
33template <typename T = void, typename Allocator = void>
34class [[nodiscard]] Task : public detail::TaskBase<T, Allocator> {
35public:
36 using Base = detail::TaskBase<T, Allocator>;
37 using Base::Base;
38
49 T wait() {
50 auto handle = std::exchange(Base::handle_, nullptr);
51 Base::wait_inner_(handle);
52 auto exception = std::move(handle.promise()).exception();
53 if (exception) [[unlikely]] {
54 handle.destroy();
55 std::rethrow_exception(exception);
56 }
57 T value = std::move(handle.promise()).value();
58 handle.destroy();
59 return std::move(value);
60 }
61};
62
63template <typename Allocator>
64class [[nodiscard]]
65Task<void, Allocator> : public detail::TaskBase<void, Allocator> {
66public:
67 using Base = detail::TaskBase<void, Allocator>;
68 using Base::Base;
69
78 void wait() {
79 auto handle = std::exchange(Base::handle_, nullptr);
80 Base::wait_inner_(handle);
81 auto exception = std::move(handle.promise()).exception();
82 handle.destroy();
83 if (exception) [[unlikely]] {
84 std::rethrow_exception(exception);
85 }
86 }
87};
88
100template <typename T, typename Allocator>
102 Coro<T, Allocator> coro) noexcept {
103 auto handle = coro.release();
104 auto &promise = handle.promise();
105 promise.mark_running();
106
107 runtime.schedule_internal(&promise);
108 return {handle};
109}
110
119template <typename T, typename Allocator>
121 auto *runtime = detail::Context::current().runtime();
122 if (runtime == nullptr) [[unlikely]] {
123 throw std::logic_error("No runtime to spawn coroutine task");
124 }
125 return co_spawn(*runtime, std::move(coro));
126}
127
136inline detail::SwitchAwaiter co_switch(Runtime &runtime) noexcept {
137 return {&runtime};
138}
139
140} // namespace condy
Coroutine type used to define a coroutine function.
Definition coro.hpp:25
The event loop runtime for executing asynchronous.
Definition runtime.hpp:36
Coroutine task that runs concurrently in the runtime.
Definition task.hpp:34
T wait()
Wait synchronously for the task to complete and get the result.
Definition task.hpp:49
Coroutine definitions.
Interfaces for coroutine task management.
The main namespace for the Condy library.
Definition condy.hpp:37
Task< T, Allocator > co_spawn(Runtime &runtime, Coro< T, Allocator > coro) noexcept
Spawn a coroutine as a task in the given runtime.
Definition task.hpp:101
detail::SwitchAwaiter co_switch(Runtime &runtime) noexcept
Switch current coroutine task to the given runtime.
Definition task.hpp:136
Runtime type for running the io_uring event loop.