Files
Library/include/Void/Async/FuturePool.hpp
T

132 lines
4.0 KiB
C++

#pragma once
#include <Void/Async/Detail/Types.hpp>
#include <Void/Async/ThreadExecutor.hpp>
#include <concepts>
#include <coroutine>
#include <exception>
#include <expected>
#include <future>
#include <type_traits>
#include <utility>
// ── FuturePool ────────────────────────────────────────────────────────────────
// `std::future` adapter over a started `ThreadExecutor`.
//
// try_submit(f) is reserve-then-transfer:
// 1. one slot of the executor bound is reserved (`overloaded` / `stopped`
// are returned WITHOUT touching `f`: a rejected callable is never moved);
// 2. only after the reservation succeeded is `f` moved into a
// `std::packaged_task` owned by a self-destroying coroutine frame;
// 3. the frame is committed to the executor's normal lane.
// The reservation is released if any step throws (the exception propagates).
// Exceptions thrown by `f` are stored in the returned future. The executor
// bound counts queued, running and reserved work, so a running submission
// keeps its slot until `f` has returned.
//
// The executor must outlive the pool and must be started (or joined by the
// owner afterwards): a submission is resumed by a worker, or inline once the
// executor has been joined.
namespace Void::Async
{
namespace detail
{
// Fire-and-forget coroutine frame: created suspended, destroyed after it ran.
struct FutureJob {
struct promise_type {
FutureJob get_return_object() noexcept
{
return FutureJob{std::coroutine_handle<promise_type>::from_promise(*this)};
}
std::suspend_always initial_suspend() noexcept { return {}; }
std::suspend_never final_suspend() noexcept { return {}; }
void return_void() noexcept {}
// packaged_task stores the callable's exception in the future, so
// nothing escapes the frame.
void unhandled_exception() noexcept { std::terminate(); }
};
std::coroutine_handle<promise_type> handle{};
};
template <class R>
FutureJob run_future_job(std::packaged_task<R()> task)
{
task();
co_return;
}
// Releases a reservation unless dismissed.
class ReservationGuard
{
public:
explicit ReservationGuard(ThreadExecutor& executor) noexcept
: executor_(&executor)
{
}
ReservationGuard(const ReservationGuard&) = delete;
ReservationGuard& operator=(const ReservationGuard&) = delete;
~ReservationGuard()
{
if (executor_ != nullptr) {
executor_->release_reserved();
}
}
void dismiss() noexcept { executor_ = nullptr; }
private:
ThreadExecutor* executor_;
};
} // namespace detail
class FuturePool
{
public:
explicit FuturePool(ThreadExecutor& executor) noexcept
: executor_(&executor)
{
}
// Errors: overloaded (admitted() >= max_admitted), stopped (executor
// closed). On an error `f` is untouched. Throws only on allocation
// failure (the reservation is released first).
template <std::invocable F>
[[nodiscard]] std::expected<std::future<std::invoke_result_t<F>>, AdmissionError>
try_submit(F&& f)
{
using R = std::invoke_result_t<F>;
if (auto reserved = executor_->try_reserve_slot(); !reserved.has_value()) {
return std::unexpected{reserved.error()};
}
detail::ReservationGuard guard{*executor_};
std::packaged_task<R()> task{std::forward<F>(f)};
std::future<R> future = task.get_future();
detail::FutureJob job = detail::run_future_job<R>(std::move(task));
try {
executor_->commit_reserved(job.handle);
} catch (...) {
// The reservation is still held (guard releases it); the frame was
// never queued.
job.handle.destroy();
throw;
}
guard.dismiss();
return future;
}
private:
ThreadExecutor* executor_;
};
} // namespace Void::Async