3#include <coroio/notifier.hpp>
4#include <coroio/loop.hpp>
5#include <coroio/grow_mailbox.hpp>
60template<
typename TPoller>
67 : StopNotifier_(Loop_.
Poller())
68 , TaskNotifier_(Loop_.
Poller())
69 , Stopper_(WaitStop())
70 , TaskWaiter_(WaitTask())
80 if (Thread_.joinable()) {
87 return Loop_.Poller();
100 assert(!Thread_.joinable() &&
"TLoopThread is started once");
101 Thread_ = std::thread([
this, onFailure = std::move(onFailure)] {
106 Error_ = std::current_exception();
123 StopNotifier_.Notify();
132 if (Thread_.joinable()) {
136 std::rethrow_exception(std::exchange(Error_,
nullptr));
148 Inbox_.Push(TWork(std::move(task)));
149 TaskNotifier_.Notify();
163 void Post(std::coroutine_handle<> handle) {
164 Inbox_.Push(TWork(handle));
165 TaskNotifier_.Notify();
170 using TWork = std::variant<TLazyTask, std::coroutine_handle<>>;
175 co_await StopNotifier_.Wait();
179 TFuture<void> WaitTask() {
181 co_await TaskNotifier_.Wait();
182 while (
auto work = Inbox_.
Pop()) {
183 if (
auto* task = std::get_if<TLazyTask>(&*work)) {
184 std::move(*task).Start(&Loop_.Poller());
186 std::get<std::coroutine_handle<>>(*work).resume();
192 TLoop<TPoller> Loop_;
193 TNotifier<TPoller> StopNotifier_;
194 TNotifier<TPoller> TaskNotifier_;
195 TGrowMailbox<TWork> Inbox_;
196 TFuture<void> Stopper_;
197 TFuture<void> TaskWaiter_;
198 std::exception_ptr Error_;
std::optional< T > Pop()
Removes the oldest value, or returns nothing if there is none. Consumer only.
Definition grow_mailbox.hpp:236
A thread that runs its own event loop.
Definition loop_thread.hpp:61
void Join()
Waits for the loop thread to exit. Owner thread only; does nothing if it is not running.
Definition loop_thread.hpp:131
void Stop()
Asks the loop to exit. Any thread, any number of times, while the TLoopThread is alive: not concurren...
Definition loop_thread.hpp:122
void Submit(TFuture< void, TLazyDetachedPolicy > &&task)
Starts task on the loop thread, with the poller of the loop as its TCurrentPoller....
Definition loop_thread.hpp:147
void Post(std::coroutine_handle<> handle)
Resumes the suspended coroutine handle on the loop thread. Any thread.
Definition loop_thread.hpp:163
std::function< void(std::exception_ptr)> TFailureHook
Called on the loop thread with the exception that ended the loop, see Start().
Definition loop_thread.hpp:64
TPoller & Poller()
The poller of the loop. See the class description for which thread may use it.
Definition loop_thread.hpp:86
void Start(TFailureHook onFailure={})
Starts the loop thread. Call once, from the owner thread.
Definition loop_thread.hpp:99
~TLoopThread()
Definition loop_thread.hpp:78
Implementation of a promise/future system for coroutines.
Definition corochain.hpp:74