From 65bd92c9aa02a8dc972a67f5b18fbc931b92330b Mon Sep 17 00:00:00 2001 From: Vinnie Falco Date: Sat, 5 Dec 2026 10:10:46 -0800 Subject: [PATCH 1/6] Add work-execution.md design document Add the design document specifying the unified work (frame_cb, work_node, work_item, work_queue, root_work_base) and chain (chain_state, coro_chain, chain_queue, root_promise_base) execution model replacing continuation, chain_owner, abandon(), and abandonable. --- work-execution.md | 960 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 960 insertions(+) create mode 100644 work-execution.md diff --git a/work-execution.md b/work-execution.md new file mode 100644 index 000000000..39e631af1 --- /dev/null +++ b/work-execution.md @@ -0,0 +1,960 @@ +# Unified Work Execution and Coroutine Chain Ownership in Capy and Corosio + +- **Author:** Vinnie Falco +- **Date:** 2026-12-05 +- **Repositories:** [cppalliance/capy](https://github.com/cppalliance/capy), [cppalliance/corosio](https://github.com/cppalliance/corosio) +- **Target branch:** `develop` + +## Executive Summary + +When an execution context such as `thread_pool` or an I/O reactor (`io_context`) shuts down with work still queued, two things must happen cleanly: + +1. **Suspended C++20 coroutine stacks (`root -> a -> b -> c`) must unwind from their root** so local RAII destructors run in reverse construction order (`c`, then `b`, then `a`) and coroutine frames return to their allocators. In C++20 coroutines, frame ownership points downward (`root -> a -> b -> c`) while executor queues and synchronization wait lists hold the suspended leaf at the bottom (`c`). Calling `.destroy()` on a leaf handle frees `c` alone while stranding `a` and `b` or setting up a double-free when a parent frame later unwinds. +2. **Mixed ready queues in I/O reactors must interleave posted coroutine chains, native completion operations, and non-coroutine callbacks in a single FIFO order** without heap allocation, pointer-tagging hacks, or manual non-RAII cleanup loops. + +Previously, Capy and Corosio solved these two problems with two separate, leaky mechanisms: + +- In Capy, `chain_owner`, `continuation`, `abandon()`, and `abandonable` split a single logical fiber of execution across three structs, grew `task` from 8 bytes to 16 bytes, embedded 40 bytes of scheduling state in every leaf awaiter, allocated a `continuation[]` array on the heap in range `when_all` and `when_any`, and forced every executor and primitive to write manual `capy::abandon(c)` loops across two-pass `drain()` shutdowns. +- In Corosio, `detail::ready_queue` stole the low bit of each queued pointer (`ready_cont_bit = 1`) to distinguish a `scheduler_op*` from a `capy::continuation*`, commandeering `continuation::reserved` and `scheduler_op::q_next_` as untyped `void*` links in a non-RAII container that leaked its contents unless manually drained. + +This document specifies a unified architecture built on a single inheritance hierarchy and a clear naming convention: + +- **`chain` (`chain_state`, `coro_chain`, `chain_queue`, `root_promise_base`)** refers specifically to a suspended C++20 coroutine chain and pure coroutine-chain containers. +- **`work` (`frame_cb`, `work_node`, `work_item`, `work_queue`, `root_work_base`)** refers to the general intrusive execution hierarchy and mixed RAII containers that hold coroutine chains, native I/O operations (`scheduler_op`), and non-coroutine callbacks or sender operation states. + +At the base of the inheritance hierarchy is **`capy::frame_cb`** (`16B`), whose two function pointers (`resume` and `destroy`) match the C++20 coroutine frame prefix used by MSVC, GCC, and Clang so `cb.handle()` produces a valid `std::coroutine_handle<>`. Deriving from `frame_cb` is **`capy::work_node`** (`24B`), which adds `work_node* next = nullptr;`. Whoever wants to put an object into a `work_queue` derives their object from `work_node`. Because `capy::chain_state` (`64B`), Corosio's `detail::scheduler_op`, and arena-allocated callback wrappers all derive from `work_node`, coroutine chains, native reactor operations, and callbacks mix seamlessly in `capy::work_queue` in strict FIFO order with zero tag bits, and clean themselves up automatically via RAII when any handle or queue is destroyed. + +--- + +## Naming and Inheritance Taxonomy: What Is What + +Every public type in this design follows a strict division: **`work` is the general intrusive execution layer (coroutines, native I/O ops, callbacks, and senders); `chain` is the coroutine-chain specialization derived from `work`.** + +| Role | **`work`** (General: Coroutines + Ops + Callbacks + Senders) | **`chain`** (Coroutine Chains Specifically) | +| - | - | - | +| **Synthetic Coroutine Prefix** (`16B`) | **`capy::frame_cb`** (`{ resume, destroy, handle() }`) | *(Inherited via `work_node`)* | +| **Intrusive Queue Node Base** (`24B` / `64B`) | **`capy::work_node : frame_cb`** (adds `work_node* next`) | **`capy::chain_state : work_node`** (adds `leaf_`, `root_`, `ex_`, `alloc_`, `unwinding_`) | +| **8-Byte Move-Only RAII Handle** | **`capy::work_item`** (owns `work_node*`; implicitly converts from `coro_chain&&`) | **`capy::coro_chain`** (owns `chain_state*`) | +| **16-Byte Intrusive RAII FIFO Queue** | **`capy::work_queue`** (links `work_node*`, pops `work_item`) | **`capy::chain_queue`** (links `chain_state*`, pops `coro_chain`) | +| **Root Segment Mixin** | **`capy::root_work_base`** (non-coroutine root for Senders and Callbacks) | **`capy::root_promise_base`** (coroutine `promise_type` root) | + +### Detailed Role of Each Type + +1. **`capy::frame_cb` (`16B`, public struct):** + - Contains `void (*resume)(frame_cb*) = nullptr;` and `void (*destroy)(frame_cb*) = nullptr;`. + - Matches the two-pointer coroutine frame prefix on MSVC, GCC, and Clang so `cb.handle()` returns `std::coroutine_handle<>::from_address(this)`. + - Used anywhere a non-coroutine object needs to act as a `std::coroutine_handle<>` (including direct tail-call symmetric transfer from `await_suspend`). +2. **`capy::work_node : frame_cb` (`24B`, public struct):** + - Adds `work_node* next = nullptr;` to `frame_cb`. + - The universal intrusive base class for `capy::work_queue`. Any type that derives from `work_node` can be held by `work_item`, queued in `work_queue`, and converted to a `std::coroutine_handle<>` via `handle()`. +3. **`capy::chain_state : work_node` (`64B`, public class):** + - Derives from `work_node` and lives once inside the root of a coroutine segment (`run_async`, cross-executor `run`, `when_all` / `when_any` branch runners, `strand_invoker`, `root_promise_base`, and `root_work_base`). + - Stores `leaf_`, `root_`, `ex_`, `alloc_`, and `unwinding_`. + - Initializes `work_node::resume` to `chain_state::do_resume` (which restores the thread-local frame allocator and resumes `leaf_`) and `work_node::destroy` to `chain_state::do_destroy` (which calls `abandon()` to unwind the chain from `root_`). +4. **`capy::coro_chain` (`8B`, public move-only RAII class):** + - Owns a suspended `chain_state*` returned by `await_context::park(h)` and passed to `Executor::post(coro_chain&&)` / `dispatch(coro_chain&&)`. + - Calling `c.resume()` or `c()` calls `state_->resume()` directly inline (zero indirect call overhead on pure coroutine paths). + - Destroying a non-empty `coro_chain` or calling `c.reset()` calls `state_->abandon()`, unwinding `c -> b -> a` from the root. +5. **`capy::chain_queue` (`16B`, public move-only RAII class):** + - Intrusive FIFO queue of `coro_chain` handles linked through `chain_state::next`. + - Used by pure coroutine executors and primitives (`thread_pool`, `strand`, `async_mutex`, `async_event`). + - Destroying a non-empty `chain_queue` pops and unwinds every remaining `coro_chain`. +6. **`capy::work_item` (`8B`, public move-only RAII class):** + - Owns a `work_node*`. Implicitly constructs from `coro_chain&&` (upcasting `chain_state*` to `work_node*`) or explicitly from `work_node*`. + - Calling `w.resume()` or `w()` consumes ownership and calls `node_->resume(node_)`. + - Destroying a non-empty `work_item` or calling `w.reset()` consumes ownership and calls `node_->destroy(node_)`. + - Provides `w.target()` to inspect the underlying `work_node*` (for example, checking `w.target() == &task_op_`) and `w.release()` to disarm a static sentinel node without invoking `destroy`. +7. **`capy::work_queue` (`16B`, public move-only RAII class):** + - Intrusive FIFO queue of `work_item`s linked through `work_node::next`. + - Accepts `q.push(work_item&&)`, `q.push(coro_chain&&)`, and `q.push(work_node*)` in a single ordered queue with zero pointer-tagging. + - Destroying a non-empty `work_queue` pops and resets every remaining `work_item`. +8. **`capy::root_promise_base` and `capy::root_work_base`:** + - `root_promise_base` is the CRTP mixin for custom **coroutine** root promises. + - `root_work_base` is the CRTP base class (deriving from `frame_cb` and embedding `chain_state` + `await_context`) for custom **non-coroutine** roots such as P2300 sender `operation_state`s and callback bridges. + +```mermaid +classDiagram + class frame_cb { + +resume_fn resume + +destroy_fn destroy + +handle() coroutine_handle + } + class work_node { + +work_node* next + } + class chain_state { + -coroutine_handle leaf_ + -coroutine_handle root_ + -executor_ref ex_ + -memory_resource* alloc_ + -atomic_bool unwinding_ + +resume() + +abandon() + } + class scheduler_op { + +func_type func_ + +operator()() + +destroy() + } + class callback_work { + +F fn_ + +memory_resource* mr_ + } + class coro_chain { + -chain_state* state_ + +resume() + +reset() + } + class work_item { + -work_node* node_ + +resume() + +reset() + +target() work_node* + } + class chain_queue { + -chain_state* head_ + -chain_state* tail_ + +push(coro_chain) + +pop() coro_chain + } + class work_queue { + -work_node* head_ + -work_node* tail_ + +push(coro_chain) + +push(work_item) + +push(work_node*) + +pop() work_item + } + + frame_cb <|-- work_node + work_node <|-- chain_state + work_node <|-- scheduler_op + work_node <|-- callback_work + coro_chain --> chain_state : owns + work_item --> work_node : owns + coro_chain ..> work_item : upcasts + chain_queue o-- chain_state : links via next + work_queue o-- work_node : links via next +``` + +--- + +## Proposed Public API in Capy + +```cpp +namespace boost::capy { + +struct frame_cb; +struct work_node; +class chain_state; +class coro_chain; +class chain_queue; +class work_item; +class work_queue; +class execution_context; +class executor_ref; + +// 16-byte synthetic coroutine frame prefix. +// The two function pointers match the C++20 coroutine frame layout on MSVC, +// GCC, and Clang so handle() produces a std::coroutine_handle<> whose +// .resume() and .destroy() invoke resume(this) and destroy(this). +struct frame_cb +{ + void (*resume)(frame_cb*) = nullptr; + void (*destroy)(frame_cb*) = nullptr; + + std::coroutine_handle<> handle() noexcept + { + return std::coroutine_handle<>::from_address(static_cast(this)); + } +}; + +// 24-byte intrusive base node for objects placed into a work_queue. +// Derive custom operations, sentinels, or callback nodes from work_node. +struct work_node : frame_cb +{ + work_node* next = nullptr; +}; + +// 8-byte move-only RAII handle owning a suspended coroutine chain. +// Resuming consumes ownership; destroying while armed unwinds from the root. +class [[nodiscard]] coro_chain +{ + chain_state* state_ = nullptr; + + friend class chain_state; + friend class chain_queue; + friend class work_item; + friend class work_queue; + + explicit coro_chain(chain_state* state) noexcept; + +public: + coro_chain() = default; + coro_chain(coro_chain&& other) noexcept; + coro_chain& operator=(coro_chain&& other) noexcept; + ~coro_chain(); + + coro_chain(coro_chain const&) = delete; + coro_chain& operator=(coro_chain const&) = delete; + + // True when holding a suspended coroutine chain. + explicit operator bool() const noexcept; + + // Unwind the held chain now if armed, leaving *this empty. + void reset() noexcept; + + // Consume ownership, install the chain's frame allocator, and resume the leaf. + void resume(); + + // Callable adapter equivalent to resume(), enabling direct submission to foreign executors. + void operator()(); + + // Post *this to the chain's bound executor, consuming ownership on success. + void post(); + + // Dispatch *this through the chain's bound executor, returning a symmetric-transfer handle. + std::coroutine_handle<> dispatch(); + + // Consume ownership and return the raw leaf handle for inline symmetric transfer. + std::coroutine_handle<> release_handle() noexcept; + + // Peek at the raw leaf handle without consuming ownership. + std::coroutine_handle<> handle() const noexcept; + + // Escape hatches for kernel proactors and C void* queues (IOCP, io_uring, PostMessage, GCD). + void* release_address() noexcept; + static coro_chain from_address(void* addr) noexcept; +}; + +// 16-byte intrusive FIFO queue of coro_chain nodes stored in root promises. +// Destroying a non-empty queue pops and unwinds every remaining chain via ~coro_chain(). +class chain_queue +{ + chain_state* head_ = nullptr; + chain_state* tail_ = nullptr; + +public: + chain_queue() = default; + chain_queue(chain_queue&& other) noexcept; + chain_queue& operator=(chain_queue&& other) noexcept; + ~chain_queue(); + + chain_queue(chain_queue const&) = delete; + chain_queue& operator=(chain_queue const&) = delete; + + bool empty() const noexcept; + void push(coro_chain&& c) noexcept; + void push_front(coro_chain&& c) noexcept; + coro_chain pop() noexcept; + void splice(chain_queue&& other) noexcept; + void clear() noexcept; +}; + +// 8-byte move-only RAII handle owning any work_node (a coro_chain, a native +// I/O operation, or a callback node). +// Resuming invokes node_->resume(node_); destroying while armed invokes +// node_->destroy(node_). +class [[nodiscard]] work_item +{ + work_node* node_ = nullptr; + + friend class work_queue; + +public: + work_item() = default; + + // Take ownership of a work_node directly. + explicit work_item(work_node* node) noexcept; + + // Implicitly convert an owning coro_chain into a work_item. + work_item(coro_chain&& c) noexcept; + + work_item(work_item&& other) noexcept; + work_item& operator=(work_item&& other) noexcept; + ~work_item(); + + work_item(work_item const&) = delete; + work_item& operator=(work_item const&) = delete; + + // True when holding a work node. + explicit operator bool() const noexcept; + + // Destroy/unwind the held node now if non-empty, leaving *this empty. + void reset() noexcept; + + // Consume ownership and invoke node_->resume(node_). + void resume(); + + // Callable adapter equivalent to resume(). + void operator()(); + + // Peek at the underlying work_node pointer without consuming ownership + // (for example, to compare against a static sentinel op). + work_node* target() const noexcept; + + // Release ownership of the underlying work_node pointer without invoking + // resume or destroy (used when disarming a static sentinel op). + work_node* release() noexcept; +}; + +// 16-byte intrusive FIFO queue of work_item nodes (mixing coro_chain and +// custom work_node operations in a single queue with zero tag bits). +// Destroying a non-empty work_queue pops and resets every remaining item. +class work_queue +{ + work_node* head_ = nullptr; + work_node* tail_ = nullptr; + +public: + work_queue() = default; + work_queue(work_queue&& other) noexcept; + work_queue& operator=(work_queue&& other) noexcept; + ~work_queue(); + + work_queue(work_queue const&) = delete; + work_queue& operator=(work_queue const&) = delete; + + bool empty() const noexcept; + void push(work_item&& w) noexcept; + void push(coro_chain&& c) noexcept; + void push(work_node* node) noexcept; + void push_front(work_item&& w) noexcept; + work_item pop() noexcept; + void splice(work_queue&& other) noexcept; + void splice(work_queue& other) noexcept; + void clear() noexcept; +}; + +// Shared state for a coroutine chain segment, deriving from work_node. +class chain_state : public work_node +{ +public: + chain_state() noexcept; + chain_state(chain_state const&) = delete; + chain_state& operator=(chain_state const&) = delete; + + void bind( + std::coroutine_handle<> root, + executor_ref ex, + std::pmr::memory_resource* alloc = nullptr) noexcept; + + void bind_root(std::coroutine_handle<> self) noexcept; + void set_leaf( + std::coroutine_handle<> leaf, + std::pmr::memory_resource* alloc = nullptr) noexcept; + + std::coroutine_handle<> handle() const noexcept; + executor_ref executor() const noexcept; + bool abandoned() const noexcept; + void resume(); + void abandon() noexcept; +}; + +// Immutable environment propagated forward through ContextAwaitable::await_suspend. +struct await_context +{ + executor_ref executor; + std::stop_token stop_token; + std::pmr::memory_resource* frame_allocator = nullptr; + chain_state* chain = nullptr; + + // Record leaf handle h in the root chain state and return an armed RAII coro_chain. + coro_chain park(std::coroutine_handle<> h) const noexcept; + bool is_unwinding() const noexcept; +}; + +// CRTP mixin for custom segment-owning root coroutines. +template +class root_promise_base + : public context_awaitable_promise_base +{ +public: + void bind_chain( + std::coroutine_handle self, + executor_ref ex, + std::stop_token st = {}, + std::pmr::memory_resource* alloc = nullptr) noexcept; + + bool chain_unwound() const noexcept; + chain_state& state() noexcept; +}; + +// CRTP base for non-coroutine roots (P2300 sender operation_states and +// callback bridges) that start and await a ContextAwaitable chain. +template +class root_work_base : private frame_cb +{ +protected: + chain_state chain_; + await_context env_; + +public: + root_work_base() noexcept; + + // Bind this non-coroutine root's synthetic handle to chain_ and env_. + std::coroutine_handle<> bind_chain( + executor_ref ex, + std::stop_token st = {}, + std::pmr::memory_resource* alloc = nullptr) noexcept; +}; + +} // namespace boost::capy +``` + +### Removed Public Symbols + +- `boost::capy::continuation` (`include/boost/capy/continuation.hpp`) - replaced by `boost::capy::coro_chain` and `boost::capy::work_item`. +- `boost::capy::chain_owner` (`include/boost/capy/ex/abandon.hpp`) - replaced by `boost::capy::chain_state`, `boost::capy::root_promise_base`, and `boost::capy::root_work_base`. +- `boost::capy::abandon(continuation&)` (`include/boost/capy/ex/abandon.hpp`) - replaced by `coro_chain::~coro_chain()`, `coro_chain::reset()`, `work_item::~work_item()`, and `work_item::reset()`. +- `boost::capy::abandonable` (`include/boost/capy/ex/abandon.hpp`) - replaced by `root_promise_base::chain_unwound()`. +- `boost::corosio::detail::ready_queue`, `ready_is_continuation`, `ready_as_op`, `ready_as_cont` (`corosio/include/boost/corosio/detail/ready_queue.hpp`) - replaced by `boost::capy::work_queue` and `boost::capy::work_item`. + +--- + +## Design Priorities + +Every architectural tradeoff in this document is evaluated against five priorities, in strict order: + +1. **Performance** - preserve zero-overhead symmetric transfer, compact coroutine frames, zero steady-state heap allocations, and minimal cache footprint on the hot path. +2. **User ergonomics** - let application developers write straightforward coroutines and use `thread_pool` or I/O contexts naturally, whether shutting down via `stop_token` and `join()` or stopping a context and letting its destructor clean up. +3. **Fairly resistant to misuse** - make common mistakes fail at compile time or clean up safely through RAII rather than silently corrupting memory or leaking frames. +4. **Pushes the complexity to the implementor of the reactor/event loop** - concentrate subtle concurrency and shutdown rules inside the handful of event loops and reactors (`thread_pool`, `strand_service`, and Corosio's platform backends), which already demand expert systems engineering. +5. **Minimizes burden on the framework authors** - keep life straightforward for the many library authors who write custom coroutine task types (`ContextRunnable`), custom awaitable types (`ContextAwaitable`), sender bridges, and callback adapters. + +--- + +## Part I: Coroutine Chain Ownership (`chain`) + +### 1. Why C++20 Coroutine Teardown Is Hard + +In callback-based Boost.Asio, state moves forward by value from one completion handler into the next. At any moment, a single leaf operation sitting inside the reactor or scheduler queue owns the entire operation's state. When `io_context::shutdown()` runs, destroying that single queued handler frees everything in one step. + +Separately compiled C++20 coroutines split ownership and resumption into two opposite directions. Consider a coroutine chain `root -> a -> b -> c` suspended on a socket read or an executor queue at leaf `c`: + +- **Ownership points downward (`root -> a -> b -> c`).** `root` owns `a`'s coroutine handle, `a`'s suspended frame holds the live `detail::context_awaiter` temporary that owns `b`'s `task`, and `b`'s suspended frame holds the live `detail::context_awaiter` temporary that owns `c`'s `task`. +- **Resumption points upward (`c -> b -> a -> root`).** The executor queue, strand, or I/O operation at the bottom holds leaf handle `c`. Meanwhile `c`'s promise holds a raw continuation handle pointing to `b`, `b`'s promise points to `a`, and `a`'s promise points to `root`. + +If a shutting-down queue calls `c.destroy()` directly on the leaf handle it holds, three things go wrong: + +1. `c` is freed while `b`, `a`, and `root` remain suspended on the heap forever, leaking their frames and skipping the destructors of every local RAII variable inside `b` and `a`. +2. If anything later destroys `root` or `b`, `b`'s `~task()` calls `c.destroy()` a second time on a dangling handle, causing a double-free. +3. `c`'s local destructors run on whichever thread tore down the queue rather than on the coroutine chain's bound executor. + +By contrast, initiating `.destroy()` at `root` on the chain's executor unwinds the stack in the exact right order (`c`, then `b`, then `a`). Inside a suspended C++20 coroutine frame, `.destroy()` destroys live automatic objects in reverse order of construction. Because `a`'s local variables were constructed before `a` evaluated `co_await b()`, `a`'s `context_awaiter` temporary for `b` is destroyed first, entering `b.destroy()`, which enters `c.destroy()` before touching `b`'s locals. Leaf `c` destroys its locals and frees its frame first, followed by `b`, and finally `a` (verified by `testTeardownDestroysInnermostFirst` in `test/unit/task.cpp`). The whole problem is getting from the parked leaf `c` back to `root` cleanly and automatically. + +### 2. Problems with the Previous `continuation` + `abandon()` Design + +1. **One logical chain was fractured across three structs.** At any instant, a linear coroutine segment has one root frame, at most one suspended leaf coroutine, one executor affinity, and at most one queue residency. Previously Capy split that single identity across `await_context` (40 bytes in the root), `chain_owner` (48 bytes in the root, duplicating `continuation` and `executor_ref`), and `continuation` (24 bytes in every leaf awaiter, plus a 16-byte `executor_ref` copy in primitives such as `async_mutex::lock_awaiter` and `async_event::wait_awaiter`). +2. **Manual `capy::abandon(c)` pushed teardown burden onto every implementor.** Because `continuation` was a trivially copyable aggregate with a trivial destructor, any container or primitive holding parked coroutines had to write explicit destructor and shutdown loops calling `capy::abandon(c)`. +3. **Unconditional re-posting during shutdown forced two-pass `drain()` ceremony.** When `execution_context::shutdown()` shut down services such as `strand_service`, `chain_owner::abandon()` unconditionally called `ex_.post(self_)` back into the context that was already shutting down. Consequently, every execution context had to keep accepting `post` after `shutdown()`, run `shutdown()`, call `drain()`, call `destroy()`, and call `drain()` a second time. +4. **Silent memory corruption if a custom awaitable forgets `owner`.** Writing `continuation{h}` instead of `continuation{h, nullptr, env->owner}` compiled cleanly and passed happy-path tests, then destroyed only the leaf frame on shutdown. +5. **Trivial copyability and `post(continuation&)` invited address-stability bugs.** `Executor::post(continuation&)` linked `&c` intrusively via `c.reserved` and required `c` to stay at a stable address until dequeued, yet `continuation` was trivially copyable and movable. +6. **Hot-path size bloat and extra heap allocation in range combinators.** + - `sizeof(task)` doubled from 8 bytes to 16 bytes due to `bool lent_` on the outer `task` struct. + - Leaf awaiters in `async_mutex`, `async_event`, `async_waker`, and `test::stream` stored 40 bytes of scheduling fields (`continuation cont_` plus `executor_ref ex_`), and Corosio's `bytes_op_base`, `value_op_base`, and `void_op_base` each embedded a 24-byte `mutable capy::continuation cont_;`. + - `when_all_homogeneous_state` and `when_any` heap-allocated `std::make_unique(count)` (`runner_handles_`) just to post initial branch runners. + +### 3. Field Survey: How Other C++20 Coroutine Libraries Handle Teardown + +A survey of thirteen C++20 coroutine libraries and production frameworks shows that the ecosystem falls into six distinct approaches to tearing down a suspended chain `root -> a -> b -> c`. + +#### Method 1: Structured Drain and `KeepAlive` (Forbid Unresumed Drop) + +Used by [`folly::coro`](https://github.com/facebook/folly/tree/main/folly/coro), [`Seastar`](https://github.com/scylladb/seastar), [`userver`](https://github.com/userver-framework/userver), and [`yalantinglibs/coro_io`](https://github.com/alibaba/yalantinglibs). + +- **Mechanism:** Executors are contractually required to execute every submitted continuation before shutting down. In `folly::coro`, `BasePromise` holds a pointer-sized `Executor::KeepAlive<>` (passing zero-atomic `.get_alias()` tokens down nested `co_await` expressions), and `ThreadPoolExecutor::stop()` as well as `EventBase::~EventBase()` block until all outstanding `KeepAlive` tokens drop to zero. Dynamic tasks run inside `folly::coro::AsyncScope` or `CancellableAsyncScope`, whose destructor calls `CHECK` (aborting in both debug and release builds) if `co_await scope.joinAsync()` was skipped. +- **Tradeoffs:** Keeps `task` and executor queues lean and works naturally with symmetric transfer and completion-based kernel I/O (`io_uring` and IOCP). In exchange, application code must always cancel and await an explicit scope or gate before destroying an execution context; stopping an event loop early and letting its destructor clean up parked tasks is forbidden. + +#### Method 2: Mandatory Three-Channel Completion and `unhandled_stopped()` + +Used by C++26 `std::execution` ([P2300R10](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2024/p2300r10.html)), `std::execution::task` ([P3552R3](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2025/p3552r3.html) and [`bemanproject/task`](https://github.com/bemanproject/task)), [`NVIDIA/stdexec`](https://github.com/NVIDIA/stdexec), and [`libunifex`](https://github.com/facebookexperimental/libunifex). + +- **Mechanism:** `[exec.async.ops]` requires every started operation to complete through `set_value`, `set_error`, or `set_stopped`. Destroying an in-flight `operation_state` has undefined behavior (`[exec.opstate.general]`), and destroying an unjoined `counting_scope` ([P3149R11](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2025/p3149r11.html)) or a non-empty `run_loop` invokes `std::terminate()`. When leaf `c` cancels, it calls `set_stopped()` on `b`'s receiver, which calls `b.promise().unhandled_stopped()` instead of `b.resume()`, symmetrically transferring straight up the chain (`c -> b -> a -> root`). +- **Tradeoffs:** Exception-free $O(\text{depth})$ cancellation unwind and inline child operation states, paired with heavy awaiter and operation-state footprints (exceeding 100 bytes per non-inline `co_await` when P3552 `affine` wraps a `task_scheduler` hop) and mandatory two-phase async shutdown. + +#### Method 3: Centralized Stack Ownership Inside the Queued Handler + +Used by [`Boost.Asio`](https://github.com/boostorg/asio) (`asio::awaitable`, `asio::co_spawn`, and `detail::awaitable_thread`). + +- **Mechanism:** `co_spawn` allocates a synthetic entry-point frame (`bottom_of_stack_`), and each `co_await` keeps downward RAII ownership inside the caller's live `awaitable` temporary (`entry -> a -> b -> c`) while maintaining `caller_` and `top_of_stack_` pointers for execution. When leaf `c` suspends on an async operation or `post`, `c` detaches `bottom_of_stack_` and moves ownership of the entire `awaitable_thread` into the `awaitable_async_op_handler` queued inside `io_context`. During `io_context::shutdown()`, destroying that queued handler runs `~awaitable_thread()`, which calls `unwind_through_executor()` to post a cleanup lambda whose destruction calls `bottom_frame->destroy()`. +- **Tradeoffs:** Gives users clean synchronous `~io_context()` teardown on a single context with an 8-to-16-byte handler and shared root state. The cost is giving up C++20 symmetric transfer in favor of a `pump()` loop on every `co_await` and return, inhibiting compiler HALO optimizations, and locking coroutines into a closed `awaitable` world. + +#### Method 4: Inverted Leaf-Upward `unique_handle` Ownership + +Used by [`Boost.Cobalt`](https://github.com/boostorg/cobalt) (`cobalt::task`, `cobalt::promise`, and `cobalt::use_op`). + +- **Mechanism:** Cobalt wraps the suspended leaf coroutine handle inside `cobalt::unique_handle` inside `cobalt::completion_handler`. When `a` awaits `b`, `b`'s receiver takes ownership of `a` via `awaited_from` (`unique_handle`). On `io_context::shutdown()`, destroying `completion_handler` destroys leaf `c`, whose `~task_promise()` resets `receiver->awaited_from` to destroy `b`, chaining upward (`c -> b -> a`) in place. +- **Tradeoffs:** Preserves symmetric transfer across linear `task` chains while supporting `io_context::shutdown()`, yet turns fragile at fork, eager-coroutine, and foreign-awaitable boundaries ([boostorg/cobalt#180](https://github.com/boostorg/cobalt/issues/180), [boostorg/cobalt#198](https://github.com/boostorg/cobalt/issues/198), [boostorg/cobalt#221](https://github.com/boostorg/cobalt/issues/221), [boostorg/cobalt#224](https://github.com/boostorg/cobalt/issues/224)). + +#### Method 5: Inline Resumption with an Interruption Exception + +Used by [`concurrencpp`](https://github.com/David-Haim/concurrencpp) (`details::await_via_functor`). + +- **Mechanism:** Built-in `resume_on` and timer awaitables wrap `{ handle, &m_interrupted }` inside a 64-byte SBO `concurrencpp::task`. When `executor::shutdown()` clears its queues on the calling thread, `~await_via_functor()` sets `*m_interrupted = true` and resumes leaf `c` synchronously on the `shutdown()` thread so `c`'s `await_resume()` throws `errors::broken_task`. +- **Tradeoffs:** Violates executor and strand thread affinity during `shutdown()` and requires C++ exceptions on teardown. + +#### Method 6: Caller-Owned Top-Down `destroy()` vs. Raw-Handle Drop + +- **Caller-owned top-down `destroy()` ([`Cap'n Proto / KJ`](https://github.com/capnproto/capnproto) `kj::Promise`):** Each parent `PromiseAwaiter` uniquely owns its child via `OwnPromiseNode`, while the single-threaded `EventLoop` holds disarmable `Event*` pointers. Dropping the root `Promise` or `kj::TaskSet` synchronously cascades `coroutine.destroy()` top-down (`root -> a -> b -> c`). +- **Raw-handle drop ([`cppcoro`](https://github.com/lewissbaker/cppcoro), [`libcoro`](https://github.com/jbaldwin/libcoro), [`TooManyCooks`](https://github.com/tzcnt/TooManyCooks), and [`alibaba/async_simple`](https://github.com/alibaba/async_simple)):** Executor queues hold raw `std::coroutine_handle<>` values or trivially destructible wrappers. Stopping a context with pending work leaks `root -> a -> b -> c`. + +#### Ecosystem Comparison Matrix + +| Design | Queue Element | Leaf Awaiter Plumbing | Task-to-Task Call | Open Concepts | Unjoined Context Shutdown | Primary Limitation | +| - | - | - | - | - | - | - | +| **Capy `coro_chain` + `work_queue`** | `8B` RAII `coro_chain` / `work_item` | `0-8B` | Symmetric transfer | Yes (`ContextAwaitable`) | Automatic via `~coro_chain()` / `~work_item()` | Segment state at `when_all`/`run(ex)`; `void*` proactor queues drain via `from_address` | +| **Capy Old (`continuation` + `abandon`)** | `24B` POD `continuation` | `24-40B` | Symmetric transfer | Yes (`ContextAwaitable`) | Manual `capy::abandon(c)` + two-pass `drain()` | Manual `abandon()` everywhere; `16B` `task`; forgotten `owner` corrupts heap | +| **`Boost.Asio` (`awaitable_thread`)** | `8B` RAII `awaitable_thread` | `8-16B` | `pump()` trampoline loop | Closed (`awaitable`) | Automatic via `~awaitable_thread()` | `pump()` overhead per `co_await`; inhibits HALO; closed type system | +| **`Boost.Cobalt` (`unique_handle`)** | `8B` `unique_handle` | `4096B` SBO buffer | Symmetric transfer | Partial (raw handles leak) | Leaf `.destroy()` chains upward via `~promise` | `fork` parent UAF mid-destroy; eager `promise` order bugs; single-threaded | +| **`folly::coro` / `Seastar`** | `KeepAlive` / `task*` | `8B` alias | Symmetric transfer | Yes | Forbidden (`KeepAlive` blocks; `~AsyncScope` aborts) | Mandatory `AsyncScope` / `gate` drain before context teardown | +| **`std::execution` / `stdexec` (P2300/P3552)** | Immovable `opstate` | `>100B` with `affine` | Symmetric transfer (`stdexec::task`) | Yes (Sender/Receiver) | Forbidden (`~run_loop` / `~counting_scope` `terminate()`) | Mandatory two-phase async shutdown; large operation states | +| **`Cap'n Proto / KJ` (`kj::Promise`)** | Intrusive `Event*` | `8B` `OwnPromiseNode` | Event-loop `arm()` | Closed (`kj::Promise`) | Automatic via `~Promise()` / `~TaskSet()` | Single-threaded readiness I/O; `final_suspend` always suspends | +| **`concurrencpp` (`await_via_functor`)** | `64B` SBO `task` | `16B` | Symmetric transfer | Broken on `task(handle)` | Resumes leaf on `shutdown()` thread and throws | Violates executor thread affinity on shutdown; requires exceptions | +| **`cppcoro` / `libcoro` / `TMC` / `async_simple`** | `8B` raw `coroutine_handle<>` | `8-16B` | Symmetric transfer | Yes | Leaks chain (or deadlocks `syncAwait` / `shutdown`) | Unsafe whenever context stops with queued or racing work | + +--- + +## Part II: Unifying Coroutine Chains and Native Operations (`work` vs `chain`) + +### 4. The Tension Between Pure Coroutine Queues and Mixed Reactor Queues + +In Capy's pure coroutine facilities (`thread_pool`, `strand`, `async_mutex`, `async_event`, `async_waker`), every queued item is a suspended coroutine chain (`coro_chain`). A `chain_queue` only ever links `chain_state` nodes, and popping from it always yields a `coro_chain`. + +In an I/O reactor (`corosio::detail::reactor_scheduler` for epoll, kqueue, and select; `corosio::detail::uring_scheduler` for `io_uring`; `corosio::detail::win_scheduler` for Windows IOCP), the scheduler's ready queue (`completed_ops_` and `private_queue`) must interleave **two** kinds of work in a single FIFO order: + +1. **Posted coroutine chains (`coro_chain`)** - submitted via `io_context::executor_type::post(coro_chain&&)` (for example from `run_async`, `strand`, `async_event::set()`, `async_mutex::unlock()`, or an immediately expired `timer`). +2. **Native scheduler operations (`scheduler_op*`)** - internal reactor state machines and I/O completion envelopes: + - `task_op_` (the circulating sentinel that tells worker threads to poll `epoll_wait`, `kevent`, `select`, or `io_uring_enter` once per round of ready work so reposting coroutines never starve I/O). + - `reactor_descriptor_state` (queued when the kernel reports readiness so a worker thread runs `perform_io()` under the descriptor's mutex). + - `coro_op` subclasses (`reactor_op`, `uring_op`, `overlapped_op`, `file_op`, `raf_op`, `resolve_op`), `timer::waiter_node::completion_op`, and `signal_op` (which live inside the I/O object's implementation or timer waiter because the kernel holds their address until completion, and which must disarm `stop_cb`, decode raw kernel results into `*ec_out` and `*bytes_out`, and release `object_ref_` before dispatching the awaiting coroutine's `coro_chain`). + - `signal_drain_op_` and `submit_sqes_op_` (reactor bookkeeping operations with no coroutine attached). + +Notice two critical facts about how Corosio works: + +- **Every I/O operation in Corosio (`coro_op`, `completion_op`, `signal_op`) already owns the awaiting coroutine's `coro_chain` as a member (`capy::coro_chain cont;`)!** When the I/O operation is drained during shutdown (`op->destroy()`), `coro_op::destroy_awaiting()` simply calls `cont.reset()`, unwinding the coroutine chain from its root. And because `coro_op` holds `coro_chain cont` by value, Corosio's awaitable base classes (`bytes_op_base`, `value_op_base`, `void_op_base`) no longer need `mutable capy::continuation cont_;` at all - saving 24 bytes in every single socket, file, timer, signal, and resolver awaitable! +- **The ready queue (`completed_ops_`) must remain a single FIFO queue** so `task_op_`, completed `scheduler_op`s, and posted `coro_chain`s execute in strict arrival order. + +### 5. How `frame_cb`, `work_node`, `work_item`, and `work_queue` Eliminate Pointer Tagging + +Why did Corosio's old `ready_queue` have to steal bit 0 of each pointer (`ready_cont_bit = 1`), cast between `uintptr_t` and `void*`, and suppress GCC `-Warray-bounds` warnings? +Only because `capy::continuation` and `corosio::detail::scheduler_op` did not share a common intrusive base class! + +With `frame_cb` and `work_node`, inheritance replaces pointer tagging: + +```cpp +struct frame_cb +{ + void (*resume)(frame_cb*) = nullptr; + void (*destroy)(frame_cb*) = nullptr; + + std::coroutine_handle<> handle() noexcept + { + return std::coroutine_handle<>::from_address(static_cast(this)); + } +}; + +struct work_node : frame_cb +{ + work_node* next = nullptr; +}; +``` + +1. **`frame_cb` (`16B`):** Matches the C++20 coroutine frame prefix on MSVC, GCC, and Clang. `cb.handle()` returns a `std::coroutine_handle<>` whose `.resume()` calls `cb.resume(&cb)` and whose `.destroy()` calls `cb.destroy(&cb)`. +2. **`work_node : frame_cb` (`24B`):** Adds `work_node* next = nullptr;`. Whoever wants to put an object into a `work_queue` derives their object from `capy::work_node`. + +Now see how `capy::chain_state` and `corosio::detail::scheduler_op` both derive from `capy::work_node`: + +#### A. `capy::chain_state : public work_node` + +```cpp +class chain_state : public work_node +{ + friend class ::boost::capy::coro_chain; + friend class ::boost::capy::chain_queue; + + std::coroutine_handle<> leaf_; + std::coroutine_handle<> root_; + executor_ref ex_; + std::pmr::memory_resource* alloc_ = nullptr; + std::atomic unwinding_{false}; +#ifndef NDEBUG + bool parked_ = false; +#endif + + static void do_resume(frame_cb* p) + { + static_cast(p)->resume(); + } + + static void do_destroy(frame_cb* p) noexcept + { + static_cast(p)->abandon(); + } + +public: + chain_state() noexcept + : work_node{{&do_resume, &do_destroy}, nullptr} + { + } + // ... +}; +``` + +- When `coro_chain::resume()` is called on a `coro_chain` (for example in `thread_pool` or `strand` via `chain_queue`), it calls `state_->resume()` **directly inline** without going through the function pointer. +- When a `coro_chain` is pushed into a mixed `capy::work_queue` (implicitly converting `coro_chain&&` to `work_item`), `work_item::resume()` calls `node_->resume(node_)` (`chain_state::do_resume`), and `work_item::reset()` / `~work_item()` calls `node_->destroy(node_)` (`chain_state::do_destroy` -> `abandon()`). + +#### B. `corosio::detail::scheduler_op : public capy::work_node` + +In Corosio, `scheduler_op` derives from `capy::work_node` (replacing both `intrusive_queue::node` and `void* q_next_`): + +```cpp +class scheduler_op : public capy::work_node +{ + static void do_resume(capy::frame_cb* p) + { + (*static_cast(p))(); + } + + static void do_destroy(capy::frame_cb* p) noexcept + { + static_cast(p)->destroy(); + } + +protected: + scheduler_op() noexcept + : capy::work_node{{&do_resume, &do_destroy}, nullptr} + , func_(nullptr) + { + } + + explicit scheduler_op(func_type func) noexcept + : capy::work_node{{&do_resume, &do_destroy}, nullptr} + , func_(func) + { + } + // ... +}; +``` + +#### C. How `reactor_scheduler` and `uring_scheduler` Use `capy::work_queue` + +In `reactor_scheduler` and `uring_scheduler`: + +- `completed_ops_`, `private_queue`, and `local_ops` are all `capy::work_queue`. +- Posting a `coro_chain`: + ```cpp + completed_ops_.push(std::move(c)); + ``` +- Posting a `scheduler_op*`: + ```cpp + completed_ops_.push(op); + ``` +- Dequeuing in `do_one()`: + ```cpp + capy::work_item item = completed_ops_.pop(); + if (item.target() == &task_op_) + { + std::ignore = item.release(); // disarm static sentinel before re-pushing + // ... poll reactor and push(&task_op_) ... + } + if (item) + { + // ... unlock mutex ... + [[maybe_unused]] work_cleanup on_exit{this, &lock, ctx}; + item.resume(); // resumes coro_chain OR calls (*op)()! + return 1; + } + ``` +- Draining during shutdown (`destroy_queued`): + ```cpp + while (auto item = completed_ops_.pop()) + { + if (item.target() == &task_op_) + { + std::ignore = item.release(); + continue; + } + lock.unlock(); + item.reset(); // unwinds coro_chain from root OR calls op->destroy()! + lock.lock(); + } + ``` +- And if any `capy::work_queue` goes out of scope with items still in it, `~work_queue()` automatically pops and resets every item! + +--- + +## Part III: Bridging Non-Coroutine Code - Callbacks (BDE), Senders (`std::execution`), and Boost.Asio + +A major architectural strength of separating `work` (`frame_cb`, `work_node`, `work_item`, `work_queue`, `root_work_base`) from `chain` (`chain_state`, `coro_chain`, `chain_queue`, `root_promise_base`) is that **non-coroutine code gets first-class, zero-trampoline interoperability in every direction without imposing any Sender/Receiver or Asio completion-token cost on coroutine code.** + +### 6. Bridging Non-Coroutine Callbacks (e.g., Bloomberg BDE and `ntf-core`) + +Large pre-C++20 codebases such as Bloomberg's Basic Development Environment (`BDE`) and `ntf-core` use `std::pmr::memory_resource` / `bslma::Allocator` arenas (`bsl::allocator` inherits from `std::pmr::polymorphic_allocator`) and callback-driven executors (`bdlmt::ThreadPool`, `bmqex::Executor`, `ntci::Receiver`) without turning every RPC stub above them into a C++20 coroutine. + +`work_node`, `frame_cb`, and `root_work_base` bridge non-coroutine callback code in both directions: + +#### Direction A: Queuing a Dynamically / Arena-Allocated Callback into `work_queue` or `chain_queue` + +Any callable `F` allocated from a `std::pmr::memory_resource*` (such as a `bslma` arena or `get_recycling_memory_resource()`) derives from `capy::work_node`: + +```cpp +template +struct callback_work final : capy::work_node +{ + std::pmr::memory_resource* mr_; + F fn_; + + callback_work(std::pmr::memory_resource* mr, F&& fn) + : capy::work_node{{&do_resume, &do_destroy}, nullptr} + , mr_(mr) + , fn_(std::forward(fn)) + { + } + + static void do_resume(capy::frame_cb* p) + { + auto* self = static_cast(p); + auto* mr = self->mr_; + F local(std::move(self->fn_)); + std::pmr::polymorphic_allocator(mr).delete_object(self); + local(); + } + + static void do_destroy(capy::frame_cb* p) noexcept + { + auto* self = static_cast(p); + auto* mr = self->mr_; + std::pmr::polymorphic_allocator(mr).delete_object(self); + } +}; +``` + +- Pushing `work_item{node}` into `work_queue` queues the callback right alongside `coro_chain`s and `scheduler_op`s in FIFO order. +- If the queue executes it (`item.resume()`), `do_resume` moves the callable onto the stack, frees the `callback_work` node back to `mr_`, and invokes `local()`. +- If the context shuts down without running it (`~work_queue()` or `item.reset()`), `do_destroy` runs `~F()` and frees the node back to `mr_` without invoking the callback. +- Even on a pure `chain_queue` (or any `capy::Executor::post(coro_chain&&)`), a callback node that derives from `chain_state` and calls `bind_root(this->handle())` is a valid 1-frame `coro_chain`! + +#### Direction B: Non-Coroutine Callback Code Awaiting Any `ContextAwaitable` (Zero Coroutine Trampoline) + +In the reverse direction, a non-coroutine caller in BDE can start any `ContextAwaitable` (such as a `capy::task` or a Corosio socket/timer operation) and receive the completion in a callback **without writing a coroutine or allocating a coroutine trampoline frame**, by deriving a bridge object from `capy::root_work_base`: + +```cpp +template +struct async_callback_op final + : capy::root_work_base> +{ + std::pmr::memory_resource* mr_; + std::optional aw_; + Callback cb_; + + void start(capy::executor_ref ex, std::stop_token st = {}) + { + auto h = this->bind_chain(ex, std::move(st), mr_); + if (aw_->await_ready()) + { + on_resume(); + return; + } + auto next = capy::detail::call_await_suspend(&*aw_, h, &this->env_); + if (next != std::noop_coroutine()) + next.resume(); + } + + void on_resume() + { + if (this->chain_.abandoned()) + { + on_abandon(); + return; + } + auto* mr = mr_; + Callback cb(std::move(cb_)); + auto result = aw_->await_resume(); + std::pmr::polymorphic_allocator(mr).delete_object(this); + cb(std::move(result)); + } + + void on_abandon() noexcept + { + auto* mr = mr_; + aw_.reset(); // unwinds c -> b -> a while chain_ and env_ are still live! + std::pmr::polymorphic_allocator(mr).delete_object(this); + } +}; +``` + +Look at what happens here: + +1. `this->bind_chain(ex, st, mr_)` returns `h` (`frame_cb::handle()`), which is a synthetic `std::coroutine_handle<>` pointing to the `root_work_base` subobject. +2. `aw_->await_suspend(h, &this->env_)` starts the `ContextAwaitable` directly from normal C++ code. +3. Every child `task` or Corosio I/O operation inside `aw_` sees a standard `std::coroutine_handle<>` (`h`) and `await_context` (`&this->env_`), and allocates its coroutine frames from `mr_` (`bslma::Allocator` / `std::pmr::memory_resource*`). +4. When `aw_` finishes, its `final_suspend` symmetrically transfers to `h`, which tail-calls `on_resume()` to deliver `aw_->await_resume()` to the callback. +5. If the execution context shuts down while `aw_` is suspended three frames deep (`a -> b -> c`), `~coro_chain()` triggers `on_abandon()`, which resets `aw_` (unwinding `c`, then `b`, then `a`) and deallocates the bridge back to `mr_`. + +### 7. Consuming Any `ContextAwaitable` in a `std::execution` (P2300) Sender Pipeline + +The exact same `root_work_base` mechanism lets a C++26 `std::execution` (P2300) sender pipeline consume any `ContextAwaitable` with **zero heap allocation** (`example/awaitable-sender/awaitable_sender.hpp` and `awaitable_sender_detail.hpp`): + +```mermaid +sequenceDiagram + participant Pipe as Sender Pipeline (then / upon_error / sync_wait) + participant Op as awaitable_op_state : root_work_base + participant Aw as ContextAwaitable (task / Corosio I/O) + participant Ex as Capy Executor or P2300 Scheduler + + Pipe->>Op: ex::connect(as_sender(aw), rcvr) + Pipe->>Op: ex::start(op) + Op->>Op: Extract executor, stop_token, pmr allocator from get_env(rcvr) + Op->>Op: h = bind_chain(io_ex, st, fa) + Op->>Aw: aw.await_suspend(h, &env_) + Aw->>Ex: env->park(leaf_h) -> coro_chain + Ex-->>Aw: Resumes leaf_h (or resets coro_chain on shutdown) + Aw->>Op: Final suspend transfers to h (frame_cb) + alt Normal completion + Op->>Aw: aw.await_resume() + Op->>Pipe: set_value(rcvr, val) / set_error(rcvr, ec) / set_stopped(rcvr) + else Chain abandoned (~coro_chain) + Op->>Aw: aw_.reset() (unwinds c -> b -> a in reverse order) + Op->>Pipe: set_stopped(rcvr) + end +``` + +1. **`as_sender(CtxAw&&)`:** Wraps any `ContextAwaitable` in `awaitable_sender`, deducing P2300 `completion_signatures` (`set_value_t(...)`, `set_error_t(...)`, `set_stopped_t()`) from `aw.await_resume()`. +2. **`connect(rcvr)` -> `awaitable_op_state : root_work_base<...>`:** + - Because P2300 `operation_state` is immovable and lives at a stable address until completion, `awaitable_op_state` derives from `capy::root_work_base` (using 100% public Capy types, never touching `detail::`) and embeds `std::optional aw_` and `Receiver rcvr_` inline. + - No coroutine frame is allocated for the bridge. +3. **`start()`:** + - Queries `get_env(rcvr)` for a Capy executor (`get_context_executor`) or wraps the receiver's P2300 scheduler (`get_scheduler`) in a `scheduler_executor`. + - Bridges the receiver's stop token (`std::stop_token` passthrough or `inplace_stop_token` callback) and `std::pmr::polymorphic_allocator` resource into `this->bind_chain(io_ex, st, fa)`. + - Starts `aw_` via `call_await_suspend(&*aw_, h, &this->env_)`. +4. **Three-Channel Completion and Abandonment Safety:** + - On normal completion, `on_resume()` calls `aw_->await_resume()` and routes the result to `set_value`, `set_error`, or `set_stopped`. + - On abandonment (`~coro_chain()` during executor teardown), `on_abandon()` calls `aw_.reset()` (unwinding `c -> b -> a` in innermost-first order) and then calls `std::execution::set_stopped(std::move(rcvr_))`, satisfying P2300's `[exec.async.ops]` requirement that every started operation state completes on one of the three receiver channels. + +### 8. Bridging Boost.Asio in All Three Directions (`example/asio/`) + +`coro_chain` and `root_work_base` also simplify all three directions of Boost.Asio interoperability in `example/asio/`: + +#### Direction A: Wrapping `asio::io_context` as a Capy `Executor` (`capy_streams.cpp`, `uni_stream.hpp`) + +Because `coro_chain` is move-only, provides `void operator()()` (which calls `resume()`), and unwinds the chain in `~coro_chain()`, adapting any Asio executor to `capy::Executor` is a direct `asio::post` call: + +```cpp +void post(capy::coro_chain&& c) const +{ + net::post(ioc_->get_executor(), std::move(c)); +} +``` + +- When `ioc.run()` invokes the queued handler, Asio calls `c()`, which restores the thread-local frame allocator and resumes the leaf coroutine. +- When `~io_context()` destroys uninvoked handlers during Asio shutdown, destroying the handler runs `~coro_chain()`, which unwinds `c -> b -> a` automatically. The old `example/asio/api/abandon_guard.hpp` wrapper is deleted completely. + +#### Direction B: Awaiting Asio Operations from a Capy Coroutine (`use_capy` in `use_capy.hpp`, `asio_socket` in `capy_streams.cpp`) + +When a Capy `task` awaits an Asio async operation (`co_await sock.async_read_some(buf, use_capy)`), `await_suspend` moves `env->park(h)` directly into the Asio completion handler lambda: + +```cpp +auto handler = [this, ex = env->executor, c = env->park(h)]( + Args... args) mutable +{ + store_result(std::move(args)...); + ex.post(std::move(c)); +}; +``` + +- On normal completion, `ex.post(std::move(c))` resumes the awaiting Capy coroutine on its bound executor. +- If the Asio `io_context` shuts down and destroys the completion handler without invoking it, `~coro_chain()` inside the lambda destructor unwinds the suspended Capy coroutine chain automatically. + +#### Direction C: Calling a Capy `ContextAwaitable` (`any_stream`) from Asio Completion Tokens (`uni_stream.hpp`) + +In `example/asio/api/uni_stream.hpp`, `uni_stream` exposes a `capy::any_stream` as an Asio `AsyncReadStream` / `AsyncWriteStream` (`net::async_read(stream, buf, callback)` or `net::use_awaitable`). + +Previously, `uni_stream::initiate_async_read_some` had to call `capy::run_async(wrapper)` with an inline `[](...) -> capy::task<>` coroutine lambda - allocating **two** coroutine frames on every read or write! With `capy::root_work_base`, `uni_stream` can allocate a single non-coroutine bridge op using Asio's own `net::get_associated_allocator(handler)` (making steady-state reads and writes **zero-allocation** through Asio's thread-local recycling allocator) and drive `stream_.read_some(...)` directly via `bind_chain(...)`, just like `async_callback_op` and `awaitable_op_state`. + +--- + +## Part IV: Detailed Mechanics of the Core Solution + +### 9. Root-Resident `chain_state` + +Every coroutine run has a base coroutine frame (or `root_work_base` state) that outlives every child task in that segment. Six sites own a `chain_state`: + +1. **`run_async` (`include/boost/capy/ex/run_async.hpp`):** Stored in `run_async_trampoline::promise_type`, replacing both `continuation task_cont_` and `chain_owner owner_`. +2. **Cross-executor `run(ex)` (`include/boost/capy/ex/run.hpp`, `run_awaitable_ex`):** Stored in `boundary_trampoline::promise_type`, replacing `chain_owner segment_` and `task_cont_`. When unwound on `ex`, `boundary_trampoline` destroys the inner chain on `ex` and then resets its held parent `coro_chain` to unwind the caller chain on `caller_ex`. +3. **`when_all` and `when_any` branch runners (`include/boost/capy/when_all.hpp` and `include/boost/capy/when_any.hpp`):** Stored in each branch runner's `promise_type`. In homogeneous range overloads, Phase 1 links the newly created branch `chain_state` nodes into a stack-local list via `work_node::next` and Phase 2 posts each `coro_chain` to the executor, eliminating `runner_handles_` and its `std::make_unique(count)` heap allocation. +4. **`strand_invoker` (`src/ex/detail/strand_service.cpp`):** Stored in `strand_invoker::promise_type` inside `strand_service`'s single-slot cached frame as a 1-frame chain (`root_ == leaf_`). While a user's `coro_chain` waits inside `strand_impl::pending_`, `strand_invoker`'s own `coro_chain` is posted to the inner executor, keeping the two queue links independent. +5. **Custom root coroutines (`root_promise_base`, e.g. `corosio::tcp_server::launch_wrapper`):** User-defined root promises inherit `root_promise_base` and call `bind_chain(...)`. +6. **Non-coroutine roots (`root_work_base`, e.g. `awaitable_op_state` and callback bridges):** Non-coroutine operation states inherit `root_work_base` and call `bind_chain(...)`. + +### 10. Why `await_context const*` Stays Separate + +Same-executor environment overrides - `co_await run(sub_token)(b())` and `co_await run(sub_alloc)(b())` in `run_awaitable` (`include/boost/capy/ex/run.hpp`) - and Corosio's `timeout_awaitable` (`corosio/include/boost/corosio/detail/timeout_awaitable.hpp`) construct a child `await_context` inside the caller's frame and transfer directly into the inner operation. A single `chain_state` at the root therefore serves one or more nested `await_context` scopes along the call stack. Keeping `await_context const*` as the read-only parameter to `await_suspend(h, env)` preserves `const` correctness, keeps P4003's two-argument `await_suspend` signature intact, and lets `env->park(h)` produce an armed `coro_chain` pointing to the shared `chain_state`. + +### 11. Move-Only `coro_chain` and `post(coro_chain&&)` + +When a coroutine chain is running (`a` awaiting `task` `b`, `b` awaiting `task` `c`), control moves by symmetric transfer and `chain_state` sits untouched. Only when leaf `c` actually suspends at an executor, strand, synchronization primitive, or I/O operation does the awaiter call `env->park(h)`, which records `leaf_ = h` (and `alloc_ = env->frame_allocator`) and returns an 8-byte `coro_chain` owning that suspension. + +Passing `coro_chain&&` to `Executor::post(coro_chain&&)` and `Executor::dispatch(coro_chain&&)` gives `std::unique_ptr`-style ownership transfer: + +- **Inline `dispatch`:** Calls `c.release_handle()`, clearing `c.state_` and returning `leaf_` for symmetric transfer. +- **Queued `post`:** Moves `c` into a `chain_queue`, `work_queue`, `std::deque`, or foreign handler. If `queue_.push_back(std::move(c))` throws `std::bad_alloc` before taking ownership, `c` remains intact in the caller so `run_async` or `tcp_server::launcher` can clean up an unstarted task cleanly, whereas an uncaught exception destroys `c` as the stack unwinds. +- **Normal wakeup:** Dequeuing `c` and calling `c.resume()` (or `c()`) clears `c.state_`, installs `alloc_` as the thread-local frame allocator, and resumes `leaf_`. + +### 12. Single-Pass Shutdown via `execution_context::is_shutdown()` + +When an armed `coro_chain` (or `work_item` holding a `chain_state`) is destroyed without being resumed, `chain_state::abandon()` runs: + +- **Owner context is still running (`ex_ && !ex_.context().is_shutdown()`):** `state_->abandon()` flips `unwinding_` to `true`, sets `leaf_ = root_`, and calls `ex_.post(coro_chain{this})` so the root coroutine unwinds on its own executor thread. +- **Owner context has entered `shutdown()` (or `ex_` is empty on a 1-frame root like `strand_invoker` or `timeout_coro`):** Worker threads on that context have already stopped and joined before `shutdown()` began. `state_->abandon()` calls `std::exchange(root_, nullptr).destroy()` right in place. Inside the root `promise_type::~promise_type()` (or `root_work_base::on_abandon()`), the child task handle is destroyed before member destructors, so `c`, then `b`, then `a` unwind and return their frames to `resource_` while `chain_state`, `await_context`, and `work_guard` are still live in the root. + +### 13. Shrinking `task` Back to 8 Bytes + +In `context_awaitable_promise_base`, `env_` starts as `nullptr` at `initial_suspend()`, becomes non-null in `set_environment(env)` when awaited, and `h.done()` becomes `true` at `final_suspend()`. Checking `env_ && !h.done() && !env_->is_unwinding()` inside `context_awaitable_promise_base::destroy_coro(h)` catches illegal destruction of a live awaited task while letting `task` hold a single 8-byte `std::coroutine_handle`. + +--- + +## Part V: Evaluation Against the Five Priorities + +#### Priority 1: Performance + +- **Symmetric transfer stays untouched.** Task-to-task `co_await` and `co_return` transfer directly from frame to frame via returned `std::coroutine_handle<>` values; `coro_chain` only participates when a leaf operation actually suspends. +- **Direct inline resume on pure coroutine queues; zero tag bits on mixed work queues.** `coro_chain::resume()` calls `chain_state::resume()` directly inline without an indirect call, while `work_item::resume()` dispatches through `frame_cb::resume` without pointer tag masking or branching. +- **Smaller hot-path types and denser coroutine frames:** + +| Metric | Old Design | New Design (`coro_chain` + `work_queue`) | Improvement | +| - | - | - | - | +| `sizeof(task)` | `16B` (`handle` + `bool lent_`) | `8B` (`handle` only) | **2x smaller** (fits in one register) | +| Queue handle size | `24B` (`continuation`) | `8B` (`coro_chain` / `work_item`) | **3x smaller** in `std::deque` / `std::vector` | +| Capy leaf awaiter scheduling fields | `40B` (`continuation` + `executor_ref`) | `8B` (`coro_chain`) | **5x smaller** (`32B` saved per frame) | +| Corosio `op_base` awaitable overhead | `24B` (`mutable continuation cont_`) | `0B` (passed by value to `coro_op::cont`) | **24B saved** in every Corosio awaitable | +| Range `when_all` / `when_any` | Heap `make_unique(N)` | Intrusive stack list via `work_node::next` | **1 heap allocation eliminated** | + +#### Priority 2: User Ergonomics + +- Application code writes plain `task` coroutines, launches them with `run_async(ex)(my_task())`, and composes them with `when_all`, `when_any`, and `run` with zero nursery or scope boilerplate. +- Both structured shutdown (`stop_source.request_stop()` followed by `pool.join()`) and abrupt scope exit (`pool.stop()` followed by `~thread_pool()`, or destroying an `io_context` with pending work) destroy local RAII guards in `c -> b -> a` order and release every coroutine frame cleanly. +- Because `coro_chain` and `work_item` implement `operator()()`, bridging to Boost.Asio or any move-only callable queue is a direct `asio::post(ioc, std::move(chain))` call, deleting `example/asio/api/abandon_guard.hpp`. + +#### Priority 3: Fairly Resistant to Misuse + +- **Impossible to forget `owner`.** Armed `coro_chain` instances are constructed through `env->park(h)` (plus `coro_chain::from_address(void*)` for kernel proactor round-trips), binding the root `chain_state` automatically (`BOOST_CAPY_ASSERT(chain)` catches uninitialized environments immediately in debug builds). +- **Compile-time ownership enforcement.** `coro_chain`, `chain_queue`, `work_item`, and `work_queue` are `[[nodiscard]]` / move-only (`copy` deleted), turning accidental copies or discarded `env->park(h)` calls into compiler errors. +- **Every container is real RAII.** Destroying a `chain_queue`, a `work_queue`, a `std::deque`, or a `coro_op` in Corosio automatically unwinds or destroys every held item. +- **Zero `detail::` reach-ins.** `frame_cb`, `work_node`, `chain_state`, `coro_chain`, `chain_queue`, `work_item`, `work_queue`, `root_promise_base`, and `root_work_base` are all public types in `boost::capy`. + +#### Priority 4: Pushes the Complexity to the Implementor of the Reactor/Event Loop + +All subtle lifecycle rules live in `chain_state`, `chain_queue`, `work_queue`, and the reactor's `execution_context::service::shutdown()` implementation: + +- Thread pools and strands store `chain_queue` and clear it after stopping worker threads and calling `shutdown()`. +- Readiness and `io_uring` reactors in Corosio store `capy::work_queue`, interleave `coro_chain`s and `scheduler_op`s in a single FIFO queue, and drain via `item.reset()`. +- Kernel proactors (`IOCP`) convert `coro_chain` to a raw `void*` token via `c.release_address()` when submitting `PostQueuedCompletionStatus` with `key_continuation` and reconstruct `coro_chain::from_address(p)` when reaping completions. + +#### Priority 5: Minimizes Burden on the Framework Authors + +Framework authors writing custom coroutine task types, custom awaitables, sender bridges, and callback bridges write straightforward RAII C++20 code: + +- **Task-type authors (`ContextRunnable`):** Inherit `promise_type` from `context_awaitable_promise_base`, store a single `std::coroutine_handle h_;`, and call `promise_type::destroy_coro(h_)` in `~my_task()`. +- **Awaitable-type authors (`ContextAwaitable`):** Call `env->park(h)` at the point of suspension, store the returned `coro_chain` (or pass it by value into an I/O operation envelope), and call `chain.post()` or `dispatch_coro(ex, std::move(chain))` when ready. +- **Operation and callback authors (`work_node` / `root_work_base`):** Derive custom operations from `capy::work_node` to queue them in `capy::work_queue`, and derive non-coroutine roots (sender `operation_state`s or callback bridges) from `capy::root_work_base` to await any `ContextAwaitable` without a coroutine trampoline. From c56bb702e25217673b421b01d7d60d3fc14efcdf Mon Sep 17 00:00:00 2001 From: Vinnie Falco Date: Sat, 5 Dec 2026 10:10:58 -0800 Subject: [PATCH 2/6] Add coro_chain, chain_queue, work_queue, and root bases Add include/boost/capy/coro_chain.hpp (frame_cb, work_node, chain_state, coro_chain, chain_queue, work_item, work_queue), include/boost/capy/ex/root_promise_base.hpp (root_promise_base and root_work_base), and execution_context::is_shutdown(), along with unit tests in test/unit/ex/coro_chain.cpp. --- include/boost/capy/coro_chain.hpp | 927 ++++++++++++++++++++ include/boost/capy/ex/execution_context.hpp | 15 +- include/boost/capy/ex/root_promise_base.hpp | 240 +++++ test/unit/ex/coro_chain.cpp | 339 +++++++ 4 files changed, 1520 insertions(+), 1 deletion(-) create mode 100644 include/boost/capy/coro_chain.hpp create mode 100644 include/boost/capy/ex/root_promise_base.hpp create mode 100644 test/unit/ex/coro_chain.cpp diff --git a/include/boost/capy/coro_chain.hpp b/include/boost/capy/coro_chain.hpp new file mode 100644 index 000000000..e22f512b0 --- /dev/null +++ b/include/boost/capy/coro_chain.hpp @@ -0,0 +1,927 @@ +// +// Copyright (c) 2026 Vinnie Falco (vinnie.falco@gmail.com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// Official repository: https://github.com/cppalliance/capy +// + +#ifndef BOOST_CAPY_CORO_CHAIN_HPP +#define BOOST_CAPY_CORO_CHAIN_HPP + +#include +#include + +#include +#include +#include +#include + +namespace boost { +namespace capy { + +struct frame_cb; +struct work_node; +class chain_state; +class coro_chain; +class chain_queue; +class work_item; +class work_queue; +class execution_context; +class executor_ref; + +/** Synthetic coroutine frame prefix for callback handles and work nodes. + + The two function pointers match the C++20 coroutine frame layout + used by MSVC, GCC, and Clang so @ref handle produces a + `std::coroutine_handle<>` whose `.resume()` and `.destroy()` + invoke `resume(this)` and `destroy(this)`. + + @see @ref work_node, @ref root_work_base +*/ +struct frame_cb +{ + /// Function invoked when the synthetic handle or work item is resumed. + void (*resume)(frame_cb*) = nullptr; + + /// Function invoked when the synthetic handle or work item is destroyed. + void (*destroy)(frame_cb*) = nullptr; + + /** Return a `std::coroutine_handle<>` addressing this prefix. + + @return A coroutine handle whose `.resume()` and `.destroy()` + dispatch through @ref resume and @ref destroy. + */ + std::coroutine_handle<> handle() noexcept + { + return std::coroutine_handle<>::from_address(static_cast(this)); + } +}; + +/** Intrusive base node for objects placed into a `work_queue`. + + Derive custom operations, sentinels, or callback nodes from + `work_node` to enqueue them alongside @ref coro_chain instances + in a @ref work_queue. + + @see @ref frame_cb, @ref work_item, @ref work_queue, @ref chain_state +*/ +struct work_node : frame_cb +{ + /// Intrusive next-pointer used by `work_queue` and `chain_queue`. + work_node* next = nullptr; +}; + +/** Own a suspended coroutine chain through an 8-byte move-only RAII handle. + + A `coro_chain` represents unique ownership of a suspended coroutine + chain obtained from `await_context::park(h)`. Moving transfers + ownership; calling @ref resume, `operator()`, @ref post, + @ref dispatch, or @ref release_handle consumes ownership. If a + non-empty `coro_chain` is destroyed or @ref reset without being + resumed, it automatically unwinds the coroutine chain from its root + frame so local destructors run innermost-first (`c`, then `b`, + then `a`). + + @par Thread Safety + Distinct objects: Safe. + Shared objects: Unsafe. + + @par Example + @par !example example + + @see @ref chain_queue, @ref work_item, @ref work_queue, @ref await_context, @ref Executor +*/ +class [[nodiscard]] coro_chain +{ + chain_state* state_ = nullptr; + + friend class chain_state; + friend class chain_queue; + friend class work_item; + friend class work_queue; + + explicit coro_chain(chain_state* state) noexcept + : state_(state) + { + } + +public: + /// Construct an empty handle. + coro_chain() = default; + + /** Construct by moving ownership from `other`. + + @param other The handle to move from; left empty. + */ + coro_chain(coro_chain&& other) noexcept + : state_(std::exchange(other.state_, nullptr)) + { + } + + /** Assign by moving ownership from `other`. + + If `*this` holds a suspended chain, that chain is unwound first. + + @param other The handle to move from; left empty. + @return A reference to `*this`. + */ + coro_chain& operator=(coro_chain&& other) noexcept + { + if(this != &other) + { + reset(); + state_ = std::exchange(other.state_, nullptr); + } + return *this; + } + + /// Destroy the handle, unwinding any still-held coroutine chain. + ~coro_chain() + { + reset(); + } + + coro_chain(coro_chain const&) = delete; + coro_chain& operator=(coro_chain const&) = delete; + + /** Check whether this handle owns a suspended coroutine chain. + + @return `true` if non-empty; otherwise `false`. + */ + explicit operator bool() const noexcept + { + return state_ != nullptr; + } + + /** Unwind the held coroutine chain if non-empty, leaving `*this` empty. + */ + void reset() noexcept; + + /** Consume ownership, restore the chain's frame allocator, and resume the leaf. + + @pre `static_cast(*this)` is `true`. + */ + void resume(); + + /** Consume ownership and resume the leaf coroutine. + + Allows `coro_chain` to be submitted directly to foreign move-only + callable queues such as `boost::asio::post`. + + @pre `static_cast(*this)` is `true`. + */ + void operator()() + { + resume(); + } + + /** Post this chain to its bound executor, consuming ownership on success. + + @pre `static_cast(*this)` is `true` and bound to a `chain_state`. + */ + void post(); + + /** Dispatch this chain through its bound executor for symmetric transfer. + + @pre `static_cast(*this)` is `true` and bound to a `chain_state`. + @return The coroutine handle to transfer to, or `std::noop_coroutine()`. + */ + std::coroutine_handle<> dispatch(); + + /** Consume ownership and return the raw leaf handle for inline symmetric transfer. + + @return The leaf coroutine handle, or `{}` if `*this` was empty. + */ + std::coroutine_handle<> release_handle() noexcept; + + /** Peek at the raw leaf handle without consuming ownership. + + @return The leaf coroutine handle, or `{}` if `*this` is empty. + */ + std::coroutine_handle<> handle() const noexcept; + + /** Release ownership as an opaque pointer for C APIs and kernel proactor queues. + + The caller becomes responsible for reconstructing a `coro_chain` + via @ref from_address so the chain is either resumed or unwound. + + @return Opaque pointer representing the chain state, or `nullptr`. + */ + void* release_address() noexcept + { + return std::exchange(state_, nullptr); + } + + /** Reconstruct an owning `coro_chain` from an opaque pointer. + + @param addr Pointer previously returned by @ref release_address, + or a `chain_state*`. + @return An owning `coro_chain`. + */ + static coro_chain from_address(void* addr) noexcept + { + return coro_chain{static_cast(addr)}; + } +}; + +/** Intrusive FIFO queue of `coro_chain` nodes with zero per-item allocation. + + Links `coro_chain` handles through the `work_node::next` pointer + stored in each chain's root `chain_state`. Destroying a non-empty + `chain_queue` pops and unwinds every remaining chain through + `~coro_chain()`. + + @par Thread Safety + Distinct objects: Safe. + Shared objects: Unsafe (caller must synchronize access). + + @par Example + @par !example example + + @see @ref coro_chain, @ref work_queue +*/ +class chain_queue +{ + chain_state* head_ = nullptr; + chain_state* tail_ = nullptr; + +public: + /// Construct an empty queue. + chain_queue() = default; + + /** Construct by moving all queued chains from `other`. + + @param other The queue to move from; left empty. + */ + chain_queue(chain_queue&& other) noexcept + : head_(std::exchange(other.head_, nullptr)) + , tail_(std::exchange(other.tail_, nullptr)) + { + } + + /** Assign by moving all queued chains from `other`. + + Any chains currently in `*this` are unwound first. + + @param other The queue to move from; left empty. + @return A reference to `*this`. + */ + chain_queue& operator=(chain_queue&& other) noexcept + { + if(this != &other) + { + clear(); + head_ = std::exchange(other.head_, nullptr); + tail_ = std::exchange(other.tail_, nullptr); + } + return *this; + } + + /// Destroy the queue, unwinding any remaining chains. + ~chain_queue() + { + clear(); + } + + chain_queue(chain_queue const&) = delete; + chain_queue& operator=(chain_queue const&) = delete; + + /// Check whether the queue contains no chains. + bool empty() const noexcept + { + return head_ == nullptr; + } + + /** Enqueue a `coro_chain` at the back of the queue. + + No-op if `c` is empty. + + @param c The chain to enqueue; ownership is transferred into the queue. + */ + void push(coro_chain&& c) noexcept; + + /** Re-insert a `coro_chain` at the front of the queue. + + Used to roll back an enqueued item if posting its invoker throws. + + @param c The chain to push to the front. + */ + void push_front(coro_chain&& c) noexcept; + + /** Remove and return the front `coro_chain`, or an empty `coro_chain` if empty. + + @return The front `coro_chain`. + */ + coro_chain pop() noexcept; + + /** Append all elements of `other` to the back of `*this` in O(1). + + @param other The queue to transfer from; left empty. + */ + void splice(chain_queue&& other) noexcept; + + /// Pop and unwind every queued chain until the queue is empty. + void clear() noexcept + { + while(auto c = pop()) + c.reset(); + } +}; + +/** Own any `work_node` through an 8-byte move-only RAII handle. + + A `work_item` represents unique ownership of a `work_node` - either + a coroutine chain (`chain_state`, converted from @ref coro_chain) + or a custom operation derived from @ref work_node. Calling + @ref resume or `operator()` consumes ownership and invokes + `node->resume(node)`. Destroying a non-empty `work_item` or calling + @ref reset consumes ownership and invokes `node->destroy(node)`. + + @par Thread Safety + Distinct objects: Safe. + Shared objects: Unsafe. + + @see @ref work_node, @ref work_queue, @ref coro_chain +*/ +class [[nodiscard]] work_item +{ + work_node* node_ = nullptr; + + friend class work_queue; + +public: + /// Construct an empty handle. + work_item() = default; + + /** Construct taking ownership of `node`. + + @param node The work node to own, or `nullptr`. + */ + explicit work_item(work_node* node) noexcept + : node_(node) + { + } + + /** Construct by converting an owning `coro_chain`. + + @param c The coroutine chain to transfer ownership from; left empty. + */ + work_item(coro_chain&& c) noexcept; + + /** Construct by moving ownership from `other`. + + @param other The handle to move from; left empty. + */ + work_item(work_item&& other) noexcept + : node_(std::exchange(other.node_, nullptr)) + { + } + + /** Assign by moving ownership from `other`. + + If `*this` holds a work node, that node is destroyed first. + + @param other The handle to move from; left empty. + @return A reference to `*this`. + */ + work_item& operator=(work_item&& other) noexcept + { + if(this != &other) + { + reset(); + node_ = std::exchange(other.node_, nullptr); + } + return *this; + } + + /// Destroy the handle, destroying or unwinding any still-held work node. + ~work_item() + { + reset(); + } + + work_item(work_item const&) = delete; + work_item& operator=(work_item const&) = delete; + + /** Check whether this handle owns a work node. + + @return `true` if non-empty; otherwise `false`. + */ + explicit operator bool() const noexcept + { + return node_ != nullptr; + } + + /// Destroy or unwind the held work node if non-empty, leaving `*this` empty. + void reset() noexcept + { + if(auto* n = std::exchange(node_, nullptr)) + n->destroy(n); + } + + /** Consume ownership and invoke the work node's `resume` function. + + @pre `static_cast(*this)` is `true`. + */ + void resume() + { + BOOST_CAPY_ASSERT(node_); + auto* n = std::exchange(node_, nullptr); + n->resume(n); + } + + /** Consume ownership and invoke the work node's `resume` function. + + @pre `static_cast(*this)` is `true`. + */ + void operator()() + { + resume(); + } + + /** Peek at the underlying `work_node` pointer without consuming ownership. + + @return The held `work_node*`, or `nullptr` if empty. + */ + work_node* target() const noexcept + { + return node_; + } + + /** Release ownership of the `work_node` pointer without invoking `resume` or `destroy`. + + @return The previously held `work_node*`, or `nullptr`. + */ + work_node* release() noexcept + { + return std::exchange(node_, nullptr); + } +}; + +/** Intrusive FIFO queue of `work_item` nodes with zero per-item allocation. + + Links both @ref coro_chain instances and custom @ref work_node + operations in a single ordered queue through `work_node::next`. + Destroying a non-empty `work_queue` pops and resets every remaining + item through `~work_item()`. + + @par Thread Safety + Distinct objects: Safe. + Shared objects: Unsafe (caller must synchronize access). + + @see @ref work_item, @ref work_node, @ref chain_queue +*/ +class work_queue +{ + work_node* head_ = nullptr; + work_node* tail_ = nullptr; + + void push_node(work_node* n) noexcept + { + if(!n) + return; + n->next = nullptr; + if(tail_) + tail_->next = n; + else + head_ = n; + tail_ = n; + } + +public: + /// Construct an empty queue. + work_queue() = default; + + /** Construct by moving all queued items from `other`. + + @param other The queue to move from; left empty. + */ + work_queue(work_queue&& other) noexcept + : head_(std::exchange(other.head_, nullptr)) + , tail_(std::exchange(other.tail_, nullptr)) + { + } + + /** Assign by moving all queued items from `other`. + + Any items currently in `*this` are reset first. + + @param other The queue to move from; left empty. + @return A reference to `*this`. + */ + work_queue& operator=(work_queue&& other) noexcept + { + if(this != &other) + { + clear(); + head_ = std::exchange(other.head_, nullptr); + tail_ = std::exchange(other.tail_, nullptr); + } + return *this; + } + + /// Destroy the queue, resetting any remaining items. + ~work_queue() + { + clear(); + } + + work_queue(work_queue const&) = delete; + work_queue& operator=(work_queue const&) = delete; + + /// Check whether the queue contains no items. + bool empty() const noexcept + { + return head_ == nullptr; + } + + /** Enqueue a `work_item` at the back of the queue. + + @param w The item to enqueue; ownership is transferred into the queue. + */ + void push(work_item&& w) noexcept + { + push_node(w.release()); + } + + /** Enqueue a `coro_chain` at the back of the queue. + + @param c The chain to enqueue; ownership is transferred into the queue. + */ + void push(coro_chain&& c) noexcept; + + /** Enqueue a `work_node` at the back of the queue. + + @param node The work node to enqueue; ownership is transferred into the queue. + */ + void push(work_node* node) noexcept + { + push_node(node); + } + + /** Re-insert a `work_item` at the front of the queue. + + @param w The item to push to the front. + */ + void push_front(work_item&& w) noexcept + { + auto* n = w.release(); + if(!n) + return; + n->next = head_; + head_ = n; + if(!tail_) + tail_ = n; + } + + /** Remove and return the front `work_item`, or an empty `work_item` if empty. + + @return The front `work_item`. + */ + work_item pop() noexcept + { + if(!head_) + return {}; + auto* n = head_; + head_ = n->next; + n->next = nullptr; + if(!head_) + tail_ = nullptr; + return work_item{n}; + } + + /** Append all elements of `other` to the back of `*this` in O(1). + + @param other The queue to transfer from; left empty. + */ + void splice(work_queue&& other) noexcept + { + splice(other); + } + + /** Append all elements of `other` to the back of `*this` in O(1). + + @param other The queue to transfer from; left empty. + */ + void splice(work_queue& other) noexcept + { + if(!other.head_) + return; + if(tail_) + tail_->next = other.head_; + else + head_ = other.head_; + tail_ = other.tail_; + other.head_ = nullptr; + other.tail_ = nullptr; + } + + /// Pop and reset every queued item until the queue is empty. + void clear() noexcept + { + while(auto w = pop()) + w.reset(); + } +}; + +} // namespace capy +} // namespace boost + +#include +#include + +namespace boost { +namespace capy { + +/** Shared state for a coroutine chain segment, stored in the root promise. + + Derives from @ref work_node so a `chain_state` can be linked into + both a @ref chain_queue and a mixed @ref work_queue. + + @see @ref coro_chain, @ref chain_queue, @ref work_node, @ref root_promise_base +*/ +class chain_state : public work_node +{ + friend class coro_chain; + friend class chain_queue; + friend class work_item; + friend class work_queue; + + std::coroutine_handle<> leaf_; + std::coroutine_handle<> root_; + executor_ref ex_; + std::pmr::memory_resource* alloc_ = nullptr; + std::atomic unwinding_{false}; +#ifndef NDEBUG + bool parked_ = false; +#endif + + static void do_resume(frame_cb* p) + { + static_cast(p)->resume(); + } + + static void do_destroy(frame_cb* p) noexcept + { + static_cast(p)->abandon(); + } + +public: + /// Construct an unbound chain state with `work_node` dispatch hooks installed. + chain_state() noexcept + : work_node{{&do_resume, &do_destroy}, nullptr} + { + } + + chain_state(chain_state const&) = delete; + chain_state& operator=(chain_state const&) = delete; + + /** Bind the state to its multi-frame segment root and executor. + + @param root The root coroutine handle that owns the segment. + @param ex The executor the segment runs on; must outlive the chain. + @param alloc The initial frame allocator for the segment. + */ + void bind( + std::coroutine_handle<> root, + executor_ref ex, + std::pmr::memory_resource* alloc = nullptr) noexcept + { + root_ = root; + leaf_ = root; + ex_ = ex; + alloc_ = alloc; + } + + /** Bind the state to a standalone single-frame root coroutine. + + @param self The coroutine handle, which is both leaf and root. + */ + void bind_root(std::coroutine_handle<> self) noexcept + { + root_ = self; + leaf_ = self; + ex_ = {}; + } + + /** Record the leaf handle currently suspended on this chain. + + @param leaf The suspended coroutine handle. + @param alloc The active frame allocator for resumption. + */ + void set_leaf( + std::coroutine_handle<> leaf, + std::pmr::memory_resource* alloc = nullptr) noexcept + { +#ifndef NDEBUG + BOOST_CAPY_ASSERT(!parked_); + parked_ = true; +#endif + leaf_ = leaf; + alloc_ = alloc; + } + + /// Return the currently parked leaf handle. + std::coroutine_handle<> handle() const noexcept + { + return leaf_; + } + + /// Return the executor bound to this segment. + executor_ref executor() const noexcept + { + return ex_; + } + + /// Check whether this segment is unwinding after being abandoned. + bool abandoned() const noexcept + { + return unwinding_.load(std::memory_order_acquire); + } + +#ifndef NDEBUG + /// Return true in debug builds while a parked handle has not been consumed. + bool is_parked() const noexcept + { + return parked_; + } + + /// Mark this state as armed for an initial root launch. + void arm_root() noexcept + { + parked_ = true; + } +#else + void arm_root() noexcept {} +#endif + + /// Clear the parked debug flag and return the leaf handle. + std::coroutine_handle<> consume_leaf() noexcept + { +#ifndef NDEBUG + parked_ = false; +#endif + return leaf_; + } + + /// Resume the parked leaf coroutine with frame-allocator TLS protection. + void resume() + { +#ifndef NDEBUG + parked_ = false; +#endif + auto* saved = get_current_frame_allocator(); + set_current_frame_allocator(alloc_); + leaf_.resume(); + set_current_frame_allocator(saved); + } + + /// Post `c` through the bound executor. + void post(coro_chain&& c) + { + BOOST_CAPY_ASSERT(static_cast(ex_)); + auto ex = ex_; + ex.post(std::move(c)); + } + + /// Dispatch `c` through the bound executor. + std::coroutine_handle<> dispatch(coro_chain&& c) + { + BOOST_CAPY_ASSERT(static_cast(ex_)); + auto ex = ex_; + return ex.dispatch(std::move(c)); + } + + /// Unwind the segment on its executor, or in place if already shut down. + void abandon() noexcept + { +#ifndef NDEBUG + parked_ = false; +#endif + if(!unwinding_.exchange(true, std::memory_order_acq_rel) && + ex_ && !ex_.context().is_shutdown()) + { + leaf_ = root_; + auto ex = ex_; + ex.post(coro_chain{this}); + } + else if(root_) + { + std::exchange(root_, nullptr).destroy(); + } + } +}; + +inline void +coro_chain::reset() noexcept +{ + if(auto* s = std::exchange(state_, nullptr)) + s->abandon(); +} + +inline void +coro_chain::resume() +{ + BOOST_CAPY_ASSERT(state_); + std::exchange(state_, nullptr)->resume(); +} + +inline void +coro_chain::post() +{ + BOOST_CAPY_ASSERT(state_); + state_->post(std::move(*this)); +} + +inline std::coroutine_handle<> +coro_chain::dispatch() +{ + BOOST_CAPY_ASSERT(state_); + return state_->dispatch(std::move(*this)); +} + +inline std::coroutine_handle<> +coro_chain::release_handle() noexcept +{ + if(auto* s = std::exchange(state_, nullptr)) + return s->consume_leaf(); + return {}; +} + +inline std::coroutine_handle<> +coro_chain::handle() const noexcept +{ + return state_ ? state_->handle() : std::coroutine_handle<>{}; +} + +inline void +chain_queue::push(coro_chain&& c) noexcept +{ + auto* s = std::exchange(c.state_, nullptr); + if(!s) + return; + s->next = nullptr; + if(tail_) + tail_->next = s; + else + head_ = s; + tail_ = s; +} + +inline void +chain_queue::push_front(coro_chain&& c) noexcept +{ + auto* s = std::exchange(c.state_, nullptr); + if(!s) + return; + s->next = head_; + head_ = s; + if(!tail_) + tail_ = s; +} + +inline coro_chain +chain_queue::pop() noexcept +{ + if(!head_) + return {}; + auto* s = head_; + head_ = static_cast(s->next); + s->next = nullptr; + if(!head_) + tail_ = nullptr; + return coro_chain{s}; +} + +inline void +chain_queue::splice(chain_queue&& other) noexcept +{ + if(!other.head_) + return; + if(tail_) + tail_->next = other.head_; + else + head_ = other.head_; + tail_ = other.tail_; + other.head_ = nullptr; + other.tail_ = nullptr; +} + +inline +work_item::work_item(coro_chain&& c) noexcept + : node_(std::exchange(c.state_, nullptr)) +{ +} + +inline void +work_queue::push(coro_chain&& c) noexcept +{ + push_node(std::exchange(c.state_, nullptr)); +} + +} // namespace capy +} // namespace boost + +#endif diff --git a/include/boost/capy/ex/execution_context.hpp b/include/boost/capy/ex/execution_context.hpp index 27b0fdec5..bf56f1da1 100644 --- a/include/boost/capy/ex/execution_context.hpp +++ b/include/boost/capy/ex/execution_context.hpp @@ -14,7 +14,6 @@ #include #include #include -#include #include #include #include @@ -455,6 +454,18 @@ class BOOST_CAPY_DECL return nullptr; } + /** Check whether `shutdown()` has been called on this context. + + Returns `true` once @ref shutdown has been invoked, and `false` + before then. + + @return `true` if the context has entered shutdown; otherwise `false`. + */ + bool is_shutdown() const noexcept + { + return shutdown_; + } + protected: /** Shut down all services. @@ -567,4 +578,6 @@ execution_context( Derived* ) noexcept } // namespace capy } // namespace boost +#include + #endif diff --git a/include/boost/capy/ex/root_promise_base.hpp b/include/boost/capy/ex/root_promise_base.hpp new file mode 100644 index 000000000..693410c65 --- /dev/null +++ b/include/boost/capy/ex/root_promise_base.hpp @@ -0,0 +1,240 @@ +// +// Copyright (c) 2026 Vinnie Falco (vinnie.falco@gmail.com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// Official repository: https://github.com/cppalliance/capy +// + +#ifndef BOOST_CAPY_EX_ROOT_PROMISE_BASE_HPP +#define BOOST_CAPY_EX_ROOT_PROMISE_BASE_HPP + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace boost { +namespace capy { + +namespace detail { + +template +struct root_awaiter +{ + context_awaiter inner_; + PromiseBase* p_; + + bool await_ready() noexcept + { + return inner_.await_ready(); + } + + template + auto await_suspend(std::coroutine_handle h) noexcept + { + return inner_.await_suspend(h); + } + + auto await_resume() + { + using R = decltype(inner_.await_resume()); + bool const unwinding = p_->chain_unwound(); + if constexpr (std::is_void_v) + { + if(unwinding) + return false; + inner_.await_resume(); + return true; + } + else + { + if(unwinding) + return std::optional(); + return std::optional(inner_.await_resume()); + } + } +}; + +} // namespace detail + +/** Mixin for custom root coroutine promises that own a coroutine chain segment. + + Inherits @ref context_awaitable_promise_base and embeds both the + segment's @ref chain_state and @ref await_context. A custom root + coroutine calls @ref bind_chain from its `get_return_object()` (or + constructor) to establish itself as the segment root. + + @tparam Derived The derived promise type (CRTP pattern). + + @see @ref context_awaitable_promise_base, @ref coro_chain, @ref await_context, @ref root_work_base +*/ +template +class root_promise_base + : public context_awaitable_promise_base +{ +protected: + ::boost::capy::chain_state chain_; + await_context env_; + +public: + /** Bind the root coroutine handle, executor, stop token, and allocator. + + Initializes the embedded chain state and execution environment, + and registers the environment on this promise. + + @param self The coroutine handle of the root coroutine. + @param ex The executor the segment runs on. + @param st Optional stop token for the segment. + @param alloc Optional frame allocator for the segment. + */ + void bind_chain( + std::coroutine_handle self, + executor_ref ex, + std::stop_token st = {}, + std::pmr::memory_resource* alloc = nullptr) noexcept + { + env_.executor = ex; + env_.stop_token = std::move(st); + env_.frame_allocator = alloc; + env_.chain = &chain_; + chain_.bind(self, env_.executor, alloc); + this->set_environment(&env_); + } + + /** Check whether the segment was unwound after being abandoned. + + @return `true` if the chain was abandoned; otherwise `false`. + */ + bool chain_unwound() const noexcept + { + return chain_.abandoned(); + } + + /// Return the embedded chain state. + ::boost::capy::chain_state& state() noexcept + { + return chain_; + } + + /// Return the embedded chain state. + ::boost::capy::chain_state& chain_state() noexcept + { + return chain_; + } + + /** Transform an awaitable so `await_resume()` yields an optional or bool on unwind. + + When the segment is resumed to unwind after abandonment, the + child awaitable never completed, so `await_resume()` returns + `std::nullopt` (or `false` for `void` awaitables) without calling + the child's `await_resume()`. + + @param a The child awaitable. + @return An awaiter yielding `std::optional` or `bool`. + */ + template + decltype(auto) transform_awaitable(A&& a) + { + using Decayed = std::decay_t; + if constexpr (ContextAwaitable) + { + return detail::root_awaiter{ + detail::context_awaiter{ + std::forward(a), this}, + this}; + } + else + { + return std::forward(a); + } + } +}; + +/** CRTP base class for non-coroutine roots that start and await a `ContextAwaitable` chain. + + Provides a synthetic @ref frame_cb coroutine handle, an embedded + @ref chain_state, and an @ref await_context so non-coroutine + operation states (such as P2300 sender `operation_state`s and + callback bridges) can launch a `ContextAwaitable` without allocating + a trampoline coroutine frame. + + The derived class must provide: + - `void on_resume()` - invoked when the awaited operation completes + and transfers control to the synthetic root handle. + - `void on_abandon() noexcept` - invoked when the chain is unwound + without completing. + + @tparam Derived The derived operation state type (CRTP pattern). + + @see @ref frame_cb, @ref chain_state, @ref root_promise_base +*/ +template +class root_work_base : private frame_cb +{ + static void do_resume(frame_cb* p) + { + auto* self = static_cast(static_cast(p)); + if(self->chain_.abandoned()) + self->on_abandon(); + else + self->on_resume(); + } + + static void do_destroy(frame_cb* p) noexcept + { + static_cast(static_cast(p))->on_abandon(); + } + +protected: + ::boost::capy::chain_state chain_; + await_context env_; + +public: + /// Construct the base with `frame_cb` hooks installed. + root_work_base() noexcept + : frame_cb{&do_resume, &do_destroy} + { + } + + root_work_base(root_work_base const&) = delete; + root_work_base& operator=(root_work_base const&) = delete; + + /** Bind this non-coroutine root's synthetic handle to `chain_` and `env_`. + + @param ex The executor the segment runs on. + @param st Optional stop token for the segment. + @param alloc Optional frame allocator for the segment. + @return The synthetic `std::coroutine_handle<>` representing this root. + */ + std::coroutine_handle<> bind_chain( + executor_ref ex, + std::stop_token st = {}, + std::pmr::memory_resource* alloc = nullptr) noexcept + { + env_ = await_context{ex, std::move(st), alloc, &chain_}; + auto h = this->handle(); + chain_.bind(h, env_.executor, alloc); + return h; + } + + /// Check whether the segment was unwound after being abandoned. + bool chain_unwound() const noexcept + { + return chain_.abandoned(); + } +}; + +} // namespace capy +} // namespace boost + +#endif diff --git a/test/unit/ex/coro_chain.cpp b/test/unit/ex/coro_chain.cpp new file mode 100644 index 000000000..100c4fd51 --- /dev/null +++ b/test/unit/ex/coro_chain.cpp @@ -0,0 +1,339 @@ +// +// Copyright (c) 2026 Vinnie Falco (vinnie.falco@gmail.com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// Official repository: https://github.com/cppalliance/capy +// + +// Test that header file is self-contained. +#include +#include + +#include +#include + +#include +#include +#include +#include + +#include "test_helpers.hpp" + +namespace boost { +namespace capy { + +namespace { + +static_assert(sizeof(frame_cb) == 2 * sizeof(void*)); +static_assert(sizeof(work_node) == 3 * sizeof(void*)); +static_assert(sizeof(coro_chain) == sizeof(void*)); +static_assert(sizeof(chain_queue) == 2 * sizeof(void*)); +static_assert(sizeof(work_item) == sizeof(void*)); +static_assert(sizeof(work_queue) == 2 * sizeof(void*)); +static_assert(!std::is_copy_constructible_v); +static_assert(!std::is_copy_assignable_v); +static_assert(std::is_nothrow_move_constructible_v); +static_assert(std::is_nothrow_move_assignable_v); +static_assert(!std::is_copy_constructible_v); +static_assert(!std::is_copy_assignable_v); +static_assert(std::is_nothrow_move_constructible_v); +static_assert(std::is_nothrow_move_assignable_v); + +struct step_coro +{ + struct promise_type + { + int* resumed = nullptr; + int* destroyed = nullptr; + std::pmr::memory_resource** seen_alloc = nullptr; + + promise_type( + int& r, + int& d, + std::pmr::memory_resource** a = nullptr) noexcept + : resumed(&r) + , destroyed(&d) + , seen_alloc(a) + { + } + + ~promise_type() + { + if(destroyed) + ++*destroyed; + } + + step_coro get_return_object() noexcept + { + return {std::coroutine_handle::from_promise(*this)}; + } + + std::suspend_always initial_suspend() noexcept { return {}; } + std::suspend_always final_suspend() noexcept { return {}; } + void return_void() noexcept {} + void unhandled_exception() noexcept { std::terminate(); } + }; + + std::coroutine_handle h; +}; + +step_coro make_step( + int& resumed, + int& destroyed, + std::pmr::memory_resource** seen_alloc = nullptr) +{ + (void)destroyed; + if(seen_alloc) + *seen_alloc = get_current_frame_allocator(); + ++resumed; + co_return; +} + +struct custom_op : work_node +{ + std::vector* order = nullptr; + int* destroyed = nullptr; + int id = 0; + + custom_op(std::vector& ord, int& d, int i) noexcept + : work_node{{&do_resume, &do_destroy}, nullptr} + , order(&ord) + , destroyed(&d) + , id(i) + { + } + + static void do_resume(frame_cb* p) + { + auto* self = static_cast(p); + self->order->push_back(self->id); + } + + static void do_destroy(frame_cb* p) noexcept + { + auto* self = static_cast(p); + ++*self->destroyed; + } +}; + +} // namespace + +struct coro_chain_test +{ + void testEmptyAndMove() + { + int r = 0, d = 0; + auto sc = make_step(r, d); + chain_state st; + st.bind_root(sc.h); + st.arm_root(); + + coro_chain empty; + BOOST_TEST(!empty); + BOOST_TEST(!empty.release_handle()); + BOOST_TEST(empty.release_address() == nullptr); + + coro_chain c1 = coro_chain::from_address(&st); + BOOST_TEST(static_cast(c1)); + + coro_chain c2(std::move(c1)); + BOOST_TEST(!c1); + BOOST_TEST(static_cast(c2)); + + c1 = std::move(c2); + BOOST_TEST(static_cast(c1)); + BOOST_TEST(!c2); + + // Destroying c1 at scope exit unwinds sc.h + c1.reset(); + BOOST_TEST(!c1); + BOOST_TEST_EQ(r, 0); + BOOST_TEST_EQ(d, 1); + } + + void testResumeAndFrameAllocator() + { + int r = 0, d = 0; + std::pmr::memory_resource* seen = nullptr; + std::pmr::monotonic_buffer_resource mr; + + auto sc = make_step(r, d, &seen); + chain_state st; + st.bind_root(sc.h); + st.set_leaf(sc.h, &mr); + + auto* outer_before = get_current_frame_allocator(); + coro_chain c = coro_chain::from_address(&st); + c(); + BOOST_TEST(!c); + BOOST_TEST_EQ(r, 1); + BOOST_TEST_EQ(d, 0); + BOOST_TEST(seen == &mr); + BOOST_TEST(get_current_frame_allocator() == outer_before); + + sc.h.destroy(); + BOOST_TEST_EQ(d, 1); + } + + void testReleaseHandleAndAddress() + { + int r = 0, d = 0; + auto sc = make_step(r, d); + chain_state st; + st.bind_root(sc.h); + st.arm_root(); + + coro_chain c = coro_chain::from_address(&st); + void* addr = c.release_address(); + BOOST_TEST(!c); + BOOST_TEST(addr == &st); + BOOST_TEST_EQ(d, 0); + + coro_chain c2 = coro_chain::from_address(addr); + auto h = c2.release_handle(); + BOOST_TEST(!c2); + BOOST_TEST(h == sc.h); + BOOST_TEST_EQ(d, 0); + + h.destroy(); + BOOST_TEST_EQ(d, 1); + } + + void testQueueFifoSpliceAndRaiiClear() + { + int r1 = 0, d1 = 0, r2 = 0, d2 = 0, r3 = 0, d3 = 0; + auto sc1 = make_step(r1, d1); + auto sc2 = make_step(r2, d2); + auto sc3 = make_step(r3, d3); + + chain_state st1, st2, st3; + st1.bind_root(sc1.h); + st1.arm_root(); + st2.bind_root(sc2.h); + st2.arm_root(); + st3.bind_root(sc3.h); + st3.arm_root(); + + { + chain_queue q1; + BOOST_TEST(q1.empty()); + q1.push(coro_chain::from_address(&st1)); + BOOST_TEST(!q1.empty()); + + chain_queue q2; + q2.push(coro_chain::from_address(&st2)); + q2.push(coro_chain::from_address(&st3)); + + q1.splice(std::move(q2)); + BOOST_TEST(q2.empty()); + + auto first = q1.pop(); + BOOST_TEST(static_cast(first)); + first.resume(); + BOOST_TEST_EQ(r1, 1); + sc1.h.destroy(); + BOOST_TEST_EQ(d1, 1); + + // Leaving q1 non-empty at scope exit unwinds st2 and st3 + BOOST_TEST_EQ(d2, 0); + BOOST_TEST_EQ(d3, 0); + } + + BOOST_TEST_EQ(r2, 0); + BOOST_TEST_EQ(r3, 0); + BOOST_TEST_EQ(d2, 1); + BOOST_TEST_EQ(d3, 1); + } + + void testWorkQueueMixedFifoAndRaii() + { + std::vector order; + int op_destroyed = 0; + int r1 = 0, d1 = 0, r2 = 0, d2 = 0; + auto sc1 = make_step(r1, d1); + auto sc2 = make_step(r2, d2); + + chain_state st1, st2; + st1.bind_root(sc1.h); + st1.arm_root(); + st2.bind_root(sc2.h); + st2.arm_root(); + + custom_op op1{order, op_destroyed, 10}; + custom_op op2{order, op_destroyed, 20}; + custom_op sentinel{order, op_destroyed, 99}; + + { + work_queue wq; + BOOST_TEST(wq.empty()); + + wq.push(&op1); + wq.push(coro_chain::from_address(&st1)); + wq.push(&sentinel); + wq.push(&op2); + wq.push(coro_chain::from_address(&st2)); + + // 1. Pop op1 and resume + auto w1 = wq.pop(); + BOOST_TEST(w1.target() == &op1); + w1.resume(); + BOOST_TEST_EQ(order.size(), 1u); + BOOST_TEST_EQ(order[0], 10); + + // 2. Pop st1 (coro_chain converted to work_item) and resume + auto w2 = wq.pop(); + BOOST_TEST(w2.target() == &st1); + w2(); + BOOST_TEST_EQ(r1, 1); + sc1.h.destroy(); + BOOST_TEST_EQ(d1, 1); + + // 3. Pop sentinel and disarm via release() + auto w3 = wq.pop(); + BOOST_TEST(w3.target() == &sentinel); + BOOST_TEST(w3.release() == &sentinel); + BOOST_TEST(!w3); + + // Remaining in wq: op2 and st2 -> destroyed by ~work_queue() + BOOST_TEST_EQ(op_destroyed, 0); + BOOST_TEST_EQ(d2, 0); + } + + BOOST_TEST_EQ(op_destroyed, 1); + BOOST_TEST_EQ(r2, 0); + BOOST_TEST_EQ(d2, 1); + } + + void testExecutionContextIsShutdown() + { + struct dummy_ctx : execution_context + { + dummy_ctx() : execution_context(this) {} + void do_shutdown() noexcept { shutdown(); } + }; + + dummy_ctx ctx; + BOOST_TEST(!ctx.is_shutdown()); + ctx.do_shutdown(); + BOOST_TEST(ctx.is_shutdown()); + } + + void run() + { + testEmptyAndMove(); + testResumeAndFrameAllocator(); + testReleaseHandleAndAddress(); + testQueueFifoSpliceAndRaiiClear(); + testWorkQueueMixedFifoAndRaii(); + testExecutionContextIsShutdown(); + } +}; + +TEST_SUITE( + coro_chain_test, + "boost.capy.ex.coro_chain"); + +} // namespace capy +} // namespace boost From 5fd4618f73ff66c1d7b27b237c06b6062dfdbe6f Mon Sep 17 00:00:00 2001 From: Vinnie Falco Date: Sat, 5 Dec 2026 10:11:20 -0800 Subject: [PATCH 3/6] Cut over core library headers and sources to coro_chain Switch await_context, Executor, executor_ref, any_executor, task, run_async, run, when_all, when_any, thread_pool, strand, synchronization primitives, and test::run_blocking from continuation and chain_owner to coro_chain, chain_state, and chain_queue. Move lent-frame tracking into context_awaitable_promise_base so task shrinks to 8 bytes, and remove the runner_handles_ heap allocation from range when_all and when_any. --- include/boost/capy/concept/executor.hpp | 9 +- include/boost/capy/detail/context_awaiter.hpp | 3 + include/boost/capy/ex/any_executor.hpp | 24 ++-- include/boost/capy/ex/async_event.hpp | 16 +-- include/boost/capy/ex/async_mutex.hpp | 34 ++---- include/boost/capy/ex/async_waker.hpp | 18 +-- include/boost/capy/ex/await_context.hpp | 52 +++++--- .../ex/context_awaitable_promise_base.hpp | 33 ++++- .../boost/capy/ex/detail/strand_service.hpp | 6 +- include/boost/capy/ex/executor_ref.hpp | 25 ++-- include/boost/capy/ex/run.hpp | 34 +++--- include/boost/capy/ex/run_async.hpp | 34 +++--- include/boost/capy/ex/strand.hpp | 19 ++- include/boost/capy/ex/thread_pool.hpp | 9 +- include/boost/capy/io/write_now.hpp | 3 +- include/boost/capy/task.hpp | 22 +--- include/boost/capy/test/run_blocking.hpp | 12 +- include/boost/capy/test/stream.hpp | 26 ++-- include/boost/capy/when_all.hpp | 110 ++++++++++------- include/boost/capy/when_any.hpp | 112 ++++++++++------- src/ex/detail/strand_queue.hpp | 109 +++-------------- src/ex/detail/strand_service.cpp | 58 ++++----- src/ex/thread_pool.cpp | 63 ++++------ src/test/run_blocking.cpp | 38 +++--- test/unit/test_helpers.hpp | 115 ++++++++++++------ 25 files changed, 489 insertions(+), 495 deletions(-) diff --git a/include/boost/capy/concept/executor.hpp b/include/boost/capy/concept/executor.hpp index 659a1ef87..a4f83f055 100644 --- a/include/boost/capy/concept/executor.hpp +++ b/include/boost/capy/concept/executor.hpp @@ -12,11 +12,12 @@ #define BOOST_CAPY_CONCEPT_EXECUTOR_HPP #include -#include +#include #include #include #include +#include namespace boost { namespace capy { @@ -173,7 +174,7 @@ template concept Executor = std::is_nothrow_copy_constructible_v && std::is_nothrow_move_constructible_v && - requires(E& e, E const& ce, E const& ce2, continuation c) { + requires(E& e, E const& ce, E const& ce2, coro_chain c) { { ce == ce2 } noexcept -> std::convertible_to; { ce.context() } noexcept; requires std::is_lvalue_reference_v && @@ -183,8 +184,8 @@ concept Executor = { ce.on_work_started() } noexcept; { ce.on_work_finished() } noexcept; - { ce.dispatch(c) } -> std::same_as>; - { ce.post(c) }; + { ce.dispatch(std::move(c)) } -> std::same_as>; + { ce.post(std::move(c)) }; }; // end::executor_concept[] diff --git a/include/boost/capy/detail/context_awaiter.hpp b/include/boost/capy/detail/context_awaiter.hpp index 408989e58..60e651ed9 100644 --- a/include/boost/capy/detail/context_awaiter.hpp +++ b/include/boost/capy/detail/context_awaiter.hpp @@ -117,6 +117,9 @@ struct context_awaiter */ decltype(auto) await_resume() { +#ifndef NDEBUG + BOOST_CAPY_ASSERT(!p_->environment()->is_parked()); +#endif set_current_frame_allocator(p_->environment()->frame_allocator); return a_.await_resume(); } diff --git a/include/boost/capy/ex/any_executor.hpp b/include/boost/capy/ex/any_executor.hpp index 178e7876b..2a04725ce 100644 --- a/include/boost/capy/ex/any_executor.hpp +++ b/include/boost/capy/ex/any_executor.hpp @@ -12,12 +12,13 @@ #define BOOST_CAPY_ANY_EXECUTOR_HPP #include -#include +#include #include #include #include #include #include +#include namespace boost { namespace capy { @@ -91,8 +92,8 @@ class any_executor virtual execution_context& context() const noexcept = 0; virtual void on_work_started() const noexcept = 0; virtual void on_work_finished() const noexcept = 0; - virtual std::coroutine_handle<> dispatch(continuation&) const = 0; - virtual void post(continuation&) const = 0; + virtual std::coroutine_handle<> dispatch(coro_chain&&) const = 0; + virtual void post(coro_chain&&) const = 0; virtual bool equals(impl_base const*) const noexcept = 0; virtual detail::type_info const& target_type() const noexcept = 0; virtual void const* target_ptr() const noexcept = 0; @@ -124,14 +125,14 @@ class any_executor ex_.on_work_finished(); } - std::coroutine_handle<> dispatch(continuation& c) const override + std::coroutine_handle<> dispatch(coro_chain&& c) const override { - return ex_.dispatch(c); + return ex_.dispatch(std::move(c)); } - void post(continuation& c) const override + void post(coro_chain&& c) const override { - ex_.post(c); + ex_.post(std::move(c)); } bool equals(impl_base const* other) const noexcept override @@ -274,9 +275,9 @@ class any_executor @return A handle for symmetric transfer or `std::noop_coroutine()`. */ - std::coroutine_handle<> dispatch(continuation& c) const + std::coroutine_handle<> dispatch(coro_chain&& c) const { - return p_->dispatch(c); + return p_->dispatch(std::move(c)); } /** Post a continuation to the wrapped executor. @@ -291,11 +292,10 @@ class any_executor Propagates any exception from the wrapped executor. @param c The continuation to post for resumption. - Must remain at a stable address until dequeued. */ - void post(continuation& c) const + void post(coro_chain&& c) const { - p_->post(c); + p_->post(std::move(c)); } /** Compare two executor wrappers for equality. diff --git a/include/boost/capy/ex/async_event.hpp b/include/boost/capy/ex/async_event.hpp index 0756cca8f..c23c4a833 100644 --- a/include/boost/capy/ex/async_event.hpp +++ b/include/boost/capy/ex/async_event.hpp @@ -13,7 +13,7 @@ #include #include -#include +#include #include #include #include @@ -112,7 +112,7 @@ class async_event friend class async_event; async_event* e_; - continuation cont_; + coro_chain chain_; executor_ref ex_; // Declared before stop_cb_buf_: the callback @@ -133,7 +133,7 @@ class async_event true, std::memory_order_acq_rel)) { self_->canceled_ = true; - self_->ex_.post(self_->cont_); + self_->ex_.post(std::move(self_->chain_)); } } }; @@ -171,6 +171,7 @@ class async_event stop_cb_().~stop_cb_t(); if(list_) list_->remove(this); + std::ignore = chain_.release_handle(); } /** Construct an awaiter for the given event. @@ -195,7 +196,7 @@ class async_event */ wait_awaiter(wait_awaiter&& o) noexcept : e_(o.e_) - , cont_(o.cont_) + , chain_(std::move(o.chain_)) , ex_(o.ex_) , claimed_(o.claimed_.load( std::memory_order_relaxed)) @@ -274,8 +275,7 @@ class async_event canceled_ = true; return h; } - cont_.h = h; - cont_.owner = env->owner; + chain_ = env->park(h); ex_ = env->executor; e_->waiters_.push_back(this); list_ = &e_->waiters_; @@ -360,7 +360,7 @@ class async_event if(!w->claimed_.exchange(true, std::memory_order_acq_rel)) { w->canceled_ = true; - w->ex_.post(w->cont_); + w->ex_.post(std::move(w->chain_)); } } } @@ -395,7 +395,7 @@ class async_event while(auto* w = claimed.pop_front()) { w->list_ = nullptr; - w->ex_.post(w->cont_); + w->ex_.post(std::move(w->chain_)); } } diff --git a/include/boost/capy/ex/async_mutex.hpp b/include/boost/capy/ex/async_mutex.hpp index 0b2e4371d..a23eb9f9c 100644 --- a/include/boost/capy/ex/async_mutex.hpp +++ b/include/boost/capy/ex/async_mutex.hpp @@ -13,7 +13,7 @@ #include #include -#include +#include #include #include #include @@ -164,7 +164,7 @@ class async_mutex friend class async_mutex; async_mutex* m_; - continuation cont_; + coro_chain chain_; executor_ref ex_; // These members must be declared before stop_cb_buf_ @@ -190,7 +190,7 @@ class async_mutex true, std::memory_order_acq_rel)) { self_->canceled_ = true; - self_->ex_.post(self_->cont_); + self_->ex_.post(std::move(self_->chain_)); } } }; @@ -214,21 +214,6 @@ class async_mutex } public: - /** Destroy the awaiter, leaving the mutex unable to reach it. - - If the awaiter is suspended in the wait queue, destroys the - stop callback and unlinks the awaiter. Neither `unlock()` nor - the stop callback can then reach a destroyed awaiter when the - coroutine frame is torn down while suspended. - - If the lock was handed to this awaiter and the coroutine is - destroyed before it resumes, the lock is released to the next - waiter. - - @pre Called on the executor thread. The stop callback may fire - from any thread, so destroying a still-suspended awaiter from - another thread is undefined. - */ ~lock_awaiter() { if(active_) @@ -237,6 +222,10 @@ class async_mutex } if(in_list_) m_->waiters_.remove(this); + // If this awaiter is being destroyed while still suspended, + // the enclosing coroutine chain is already unwinding from its + // root; disarm chain_ so ~coro_chain() does not re-enter abandon(). + std::ignore = chain_.release_handle(); // Handed the lock but destroyed before resuming: pass it on. if(granted_) { @@ -269,7 +258,7 @@ class async_mutex */ lock_awaiter(lock_awaiter&& o) noexcept : m_(o.m_) - , cont_(o.cont_) + , chain_(std::move(o.chain_)) , ex_(o.ex_) , claimed_(o.claimed_.load( std::memory_order_relaxed)) @@ -359,8 +348,7 @@ class async_mutex canceled_ = true; return h; } - cont_.h = h; - cont_.owner = env->owner; + chain_ = env->park(h); ex_ = env->executor; m_->waiters_.push_back(this); in_list_ = true; @@ -599,7 +587,7 @@ class async_mutex if(!w->claimed_.exchange(true, std::memory_order_acq_rel)) { w->canceled_ = true; - w->ex_.post(w->cont_); + w->ex_.post(std::move(w->chain_)); } } } @@ -676,7 +664,7 @@ class async_mutex auto* waiter = grant_next(); if(!waiter) break; - waiter->ex_.post(waiter->cont_); + waiter->ex_.post(std::move(waiter->chain_)); if(scope.gone) return; } diff --git a/include/boost/capy/ex/async_waker.hpp b/include/boost/capy/ex/async_waker.hpp index e66e538f0..02b0c7f25 100644 --- a/include/boost/capy/ex/async_waker.hpp +++ b/include/boost/capy/ex/async_waker.hpp @@ -12,7 +12,7 @@ #define BOOST_CAPY_EX_ASYNC_WAKER_HPP #include -#include +#include #include #include #include @@ -148,7 +148,7 @@ class async_waker friend class async_waker; async_waker* waker_; - continuation cont_; + coro_chain chain_; executor_ref ex_; // Declared before stop_cb_buf_: the callback accesses @@ -175,7 +175,7 @@ class async_waker self_->canceled_ = true; self_->claimed_.store( true, std::memory_order_release); - self_->ex_.post(self_->cont_); + self_->ex_.post(std::move(self_->chain_)); } } }; @@ -222,6 +222,7 @@ class async_waker std::memory_order_acq_rel, std::memory_order_acquire); } + std::ignore = chain_.release_handle(); } /** Construct an awaiter for the given waker. @@ -246,7 +247,7 @@ class async_waker */ wait_awaiter(wait_awaiter&& o) noexcept : waker_(o.waker_) - , cont_(o.cont_) + , chain_(std::move(o.chain_)) , ex_(o.ex_) , canceled_(o.canceled_) , active_(std::exchange(o.active_, false)) @@ -344,8 +345,7 @@ class async_waker canceled_ = true; return h; } - cont_.h = h; - cont_.owner = env->owner; + chain_ = env->park(h); ex_ = env->executor; waker_->waiter_ = this; @@ -372,6 +372,7 @@ class async_waker published_ = false; stop_cb_().~stop_cb_t(); active_ = false; + std::ignore = chain_.release_handle(); waker_->st_.store( state_empty, std::memory_order_release); return h; @@ -384,6 +385,7 @@ class async_waker if(env->stop_token.stop_requested()) { published_ = false; + std::ignore = chain_.release_handle(); waker_->st_.store( state_empty, std::memory_order_release); canceled_ = true; @@ -448,7 +450,7 @@ class async_waker } w->canceled_ = true; w->claimed_.store(true, std::memory_order_release); - w->ex_.post(w->cont_); + w->ex_.post(std::move(w->chain_)); } } @@ -551,7 +553,7 @@ class async_waker w->stop_cb_().~cb_t(); w->active_ = false; w->claimed_.store(true, std::memory_order_release); - w->ex_.post(w->cont_); + w->ex_.post(std::move(w->chain_)); return; } } // LCOV_EXCL_LINE armed CAS lost to a stop callback or failed spuriously diff --git a/include/boost/capy/ex/await_context.hpp b/include/boost/capy/ex/await_context.hpp index 9af0f224c..e97149bc8 100644 --- a/include/boost/capy/ex/await_context.hpp +++ b/include/boost/capy/ex/await_context.hpp @@ -12,6 +12,7 @@ #define BOOST_CAPY_AWAIT_CONTEXT_HPP #include +#include #include #include @@ -21,8 +22,6 @@ namespace boost { namespace capy { -class chain_owner; - /** Carries the executor, stop token, and frame allocator through a coroutine chain. This struct bundles the environment passed through coroutine @@ -48,7 +47,7 @@ class chain_owner; @par Example @par !example example - @see @ref ContextAwaitable, @ref ContextRunnable + @see @ref ContextAwaitable, @ref ContextRunnable, @ref coro_chain */ struct await_context { @@ -64,23 +63,44 @@ struct await_context */ std::pmr::memory_resource* frame_allocator = nullptr; - /** The owner of the chain segment running in this environment. + /** The shared chain state for the segment running in this environment. Set by whatever started the segment (`run_async`, `run` on - another executor, a `when_all` or `when_any` branch). An - awaitable that parks or queues a coroutine copies it into the - @ref continuation it keeps, so a holder can @ref abandon the - segment. Null when nothing owns the segment. - - Some code starts a task under an environment it builds itself, - rather than through `run_async`, `run` or a join. Such code must - either own the segment, binding a @ref chain_owner, or ensure - nothing awaits the coroutines that could be abandoned. With no - owner, @ref abandon destroys only the frame it is given, and any - frame awaiting it is left holding a destroyed frame. + another executor, a `when_all` or `when_any` branch, or + @ref root_promise_base). An awaitable that parks or queues a + coroutine calls @ref park to obtain an owning @ref coro_chain. + */ + chain_state* chain = nullptr; + + /** Record `h` as the parked leaf coroutine and return an owning `coro_chain`. + + @pre `chain != nullptr` + @param h The suspended leaf coroutine handle. + @return An armed @ref coro_chain owning the suspended chain. */ - chain_owner* owner = nullptr; + coro_chain park(std::coroutine_handle<> h) const noexcept + { + BOOST_CAPY_ASSERT(chain); + chain->set_leaf(h, frame_allocator); + return coro_chain::from_address(chain); + } + /** Check whether the chain segment is currently unwinding after abandonment. + + @return `true` if the segment is unwinding; otherwise `false`. + */ + bool is_unwinding() const noexcept + { + return chain && chain->abandoned(); + } + +#ifndef NDEBUG + /// Return true in debug builds if a parked handle has not yet been consumed. + bool is_parked() const noexcept + { + return chain && chain->is_parked(); + } +#endif }; } // capy diff --git a/include/boost/capy/ex/context_awaitable_promise_base.hpp b/include/boost/capy/ex/context_awaitable_promise_base.hpp index 3220d38f9..ccbcb8e46 100644 --- a/include/boost/capy/ex/context_awaitable_promise_base.hpp +++ b/include/boost/capy/ex/context_awaitable_promise_base.hpp @@ -12,7 +12,6 @@ #define BOOST_CAPY_EX_CONTEXT_AWAITABLE_PROMISE_BASE_HPP #include -#include #include #include #include @@ -20,6 +19,7 @@ #include #include +#include #include #include #include @@ -118,8 +118,39 @@ class context_awaitable_promise_base { await_context const* env_ = nullptr; mutable std::coroutine_handle<> cont_{std::noop_coroutine()}; + bool lent_ = false; public: + /** Destroy a coroutine frame owned by a task, enforcing lent-frame safety. + + Calls `std::terminate()` if `h` is currently lent to an awaiting + coroutine and has not completed, unless its chain is being unwound + after abandonment. + + @param h The coroutine handle to destroy (no-op if null). + */ + static void destroy_coro(std::coroutine_handle h) noexcept + { + if(!h) + return; + auto& p = h.promise(); + if(p.lent_ && !h.done()) + { + if(!p.env_ || !p.env_->is_unwinding()) + std::terminate(); // LCOV_EXCL_LINE reached only in a death test's child process + } + h.destroy(); + } + + /** Mark this coroutine frame as lent or unlent to an awaiting caller. + + @param v `true` when `await_suspend` lends the frame; `false` in `await_resume`. + */ + void set_lent(bool v) noexcept + { + lent_ = v; + } + /** Store the continuation to resume on completion. Call this from your coroutine type's `await_suspend` overload diff --git a/include/boost/capy/ex/detail/strand_service.hpp b/include/boost/capy/ex/detail/strand_service.hpp index 8f4dc144c..b311b6163 100644 --- a/include/boost/capy/ex/detail/strand_service.hpp +++ b/include/boost/capy/ex/detail/strand_service.hpp @@ -10,7 +10,7 @@ #ifndef BOOST_CAPY_EX_DETAIL_STRAND_SERVICE_HPP #define BOOST_CAPY_EX_DETAIL_STRAND_SERVICE_HPP -#include +#include #include #include #include @@ -70,14 +70,14 @@ class BOOST_CAPY_DECL strand_service dispatch( std::shared_ptr const& impl, executor_ref ex, - continuation& c); + coro_chain&& c); /** Post to strand queue. */ static void post( std::shared_ptr const& impl, executor_ref ex, - continuation& c); + coro_chain&& c); protected: strand_service(); diff --git a/include/boost/capy/ex/executor_ref.hpp b/include/boost/capy/ex/executor_ref.hpp index dea9e4ee1..96ed69cba 100644 --- a/include/boost/capy/ex/executor_ref.hpp +++ b/include/boost/capy/ex/executor_ref.hpp @@ -13,7 +13,6 @@ #include #include -#include #include #include #include @@ -22,6 +21,7 @@ namespace boost { namespace capy { +class coro_chain; class execution_context; namespace detail { @@ -32,8 +32,8 @@ struct executor_vtable execution_context& (*context)(void const*) noexcept; void (*on_work_started)(void const*) noexcept; void (*on_work_finished)(void const*) noexcept; - void (*post)(void const*, continuation&); - std::coroutine_handle<> (*dispatch)(void const*, continuation&); + void (*post)(void const*, coro_chain&&); + std::coroutine_handle<> (*dispatch)(void const*, coro_chain&&); bool (*equals)(void const*, void const*) noexcept; detail::type_info const* type_id; }; @@ -54,12 +54,12 @@ inline constexpr executor_vtable vtable_for = { const_cast(static_cast(p))->on_work_finished(); }, // post - [](void const* p, continuation& c) { - static_cast(p)->post(c); + [](void const* p, coro_chain&& c) { + static_cast(p)->post(std::move(c)); }, // dispatch - [](void const* p, continuation& c) -> std::coroutine_handle<> { - return static_cast(p)->dispatch(c); + [](void const* p, coro_chain&& c) -> std::coroutine_handle<> { + return static_cast(p)->dispatch(std::move(c)); }, // equals [](void const* a, void const* b) noexcept -> bool { @@ -219,9 +219,9 @@ class executor_ref @return A handle for symmetric transfer or `std::noop_coroutine()`. */ - std::coroutine_handle<> dispatch(continuation& c) const + std::coroutine_handle<> dispatch(coro_chain&& c) const { - return vt_->dispatch(ex_, c); + return vt_->dispatch(ex_, std::move(c)); } /** Post a continuation to the wrapped executor. @@ -236,11 +236,10 @@ class executor_ref Propagates any exception from the wrapped executor. @param c The continuation to post for resumption. - Must remain at a stable address until dequeued. */ - void post(continuation& c) const + void post(coro_chain&& c) const { - vt_->post(ex_, c); + vt_->post(ex_, std::move(c)); } /** Compare two executor references for equality. @@ -299,4 +298,6 @@ class executor_ref } // capy } // boost +#include + #endif diff --git a/include/boost/capy/ex/run.hpp b/include/boost/capy/ex/run.hpp index 4444e6e30..d1086b9b8 100644 --- a/include/boost/capy/ex/run.hpp +++ b/include/boost/capy/ex/run.hpp @@ -16,7 +16,7 @@ #include #include #include -#include +#include #include #include #include @@ -74,8 +74,8 @@ struct boundary_trampoline : detail::process_frame_mixin { executor_ref caller_ex_; - continuation parent_; - chain_owner segment_; + coro_chain parent_; + chain_state chain_; // The awaitable's trampoline object until the inner task // completes or is unwound; null afterward. boundary_trampoline* owner_ = nullptr; @@ -90,8 +90,8 @@ struct boundary_trampoline { destroy_inner_(awaitable_); owner_ = nullptr; - auto parent = parent_; - capy::abandon(parent); + auto parent = std::move(parent_); + parent.reset(); } ~promise_type() @@ -125,7 +125,7 @@ struct boundary_trampoline { // Nothing here touches p_ after the post or the // unwind: either can destroy this frame. - if(p_->segment_.abandoned()) + if(p_->chain_.abandoned()) { p_->unwind(); } @@ -133,7 +133,7 @@ struct boundary_trampoline { p_->owner_ = nullptr; auto ex = p_->caller_ex_; - ex.post(p_->parent_); + ex.post(std::move(p_->parent_)); } return detail::symmetric_transfer( std::noop_coroutine()); @@ -219,7 +219,6 @@ struct [[nodiscard]] run_awaitable_ex await_context env_; executor_ref caller_ex_; boundary_trampoline tr_; - continuation task_cont_; bool holds_work_ = false; Task inner_; // Last: destroyed first, while env_ is still valid @@ -300,11 +299,9 @@ struct [[nodiscard]] run_awaitable_ex auto& tp = tr_.h_.promise(); tp.owner_ = &tr_; tp.caller_ex_ = caller_env->executor; - tp.parent_.h = cont; - tp.parent_.owner = caller_env->owner; + tp.parent_ = caller_env->park(cont); tp.destroy_inner_ = &run_awaitable_ex::destroy_inner; tp.awaitable_ = this; - tp.segment_.bind(tr_.h_, ex_); caller_ex_ = caller_env->executor; // Released once the parent resumes or is unwound. Not on the // post back: the parent's chain may own the executor object and @@ -316,7 +313,7 @@ struct [[nodiscard]] run_awaitable_ex auto& p = h.promise(); p.set_continuation(tr_.h_); - env_.owner = &tp.segment_; + env_.chain = &tp.chain_; env_.executor = ex_; if constexpr (InheritStopToken) env_.stop_token = caller_env->stop_token; @@ -328,19 +325,20 @@ struct [[nodiscard]] run_awaitable_ex else env_.frame_allocator = caller_env->frame_allocator; + tp.chain_.bind(tr_.h_, ex_, env_.frame_allocator); p.set_environment(&env_); - task_cont_.h = h; - task_cont_.owner = &tp.segment_; + auto task_chain = env_.park(h); try { - ex_.post(task_cont_); + ex_.post(std::move(task_chain)); } catch(...) { // The parent resumes with the exception: nothing may still // treat the task as lent or hold work for the parent. + std::ignore = task_chain.release_handle(); p.set_continuation(std::noop_coroutine()); - task_cont_.h = nullptr; + std::ignore = tp.parent_.release_handle(); tr_ = boundary_trampoline(); holds_work_ = false; caller_ex_.on_work_finished(); @@ -386,7 +384,7 @@ struct [[nodiscard]] run_awaitable // task type does when destroyed while lent. auto h = inner_.handle(); if(lent_ && h && !h.done() && - !(env_.owner && env_.owner->abandoned())) + !env_.is_unwinding()) std::terminate(); // LCOV_EXCL_LINE reached only in a death test's child process } @@ -442,7 +440,7 @@ struct [[nodiscard]] run_awaitable p.set_continuation(cont); lent_ = true; - env_.owner = caller_env->owner; + env_.chain = caller_env->chain; env_.executor = caller_env->executor; if constexpr (InheritStopToken) env_.stop_token = caller_env->stop_token; diff --git a/include/boost/capy/ex/run_async.hpp b/include/boost/capy/ex/run_async.hpp index f2b69aea7..90790a620 100644 --- a/include/boost/capy/ex/run_async.hpp +++ b/include/boost/capy/ex/run_async.hpp @@ -16,7 +16,7 @@ #include #include #include -#include +#include #include #include #include @@ -109,14 +109,10 @@ struct run_async_trampoline await_context env_; invoke_fn invoke_ = nullptr; void* task_promise_ = nullptr; - // task_h_: raw handle for frame_guard cleanup in make_trampoline. - // task_cont_: continuation wrapping the same handle for executor dispatch. - // Both must reference the same coroutine and be kept in sync. std::coroutine_handle<> task_h_; - continuation task_cont_; // Owns the task's segment: abandoning it resumes this // trampoline, or has it destroyed, to unwind the task. - chain_owner owner_; + chain_state chain_; ~promise_type() { @@ -256,14 +252,10 @@ struct run_async_trampoline await_context env_; invoke_fn invoke_ = nullptr; void* task_promise_ = nullptr; - // task_h_: raw handle for frame_guard cleanup in make_trampoline. - // task_cont_: continuation wrapping the same handle for executor dispatch. - // Both must reference the same coroutine and be kept in sync. std::coroutine_handle<> task_h_; - continuation task_cont_; // Owns the task's segment: abandoning it resumes this // trampoline, or has it destroyed, to unwind the task. - chain_owner owner_; + chain_state chain_; ~promise_type() { @@ -363,7 +355,7 @@ make_trampoline(Ex, Handlers, Alloc) // Resumed with the task unfinished: the segment was abandoned, and // destroying the task unwinds it without calling a handler. - if(!p.owner_.abandoned()) + if(!p.chain_.abandoned()) p.invoke_(p.task_promise_, p.handlers_); } @@ -549,18 +541,26 @@ class [[nodiscard]] run_async_wrapper // Setup task's continuation to return to run_async_trampoline task_promise.set_continuation(tr_.h_); - p.owner_.bind(tr_.h_, p.wg_.executor()); - p.env_ = {p.wg_.executor(), st_, p.get_resource(), &p.owner_}; + p.chain_.bind(tr_.h_, p.wg_.executor(), p.get_resource()); + p.env_ = {p.wg_.executor(), st_, p.get_resource(), &p.chain_}; task_promise.set_environment(&p.env_); // Start task through executor. // safe_resume is not needed here: TLS is already saved in the // constructor (saved_tls_) and restored in the destructor. - p.task_cont_.h = task_h; - p.task_cont_.owner = &p.owner_; // If dispatch throws, the destructor destroys the trampoline // and the unstarted task with it. - auto next = p.wg_.executor().dispatch(p.task_cont_); + auto task_chain = p.env_.park(task_h); + std::coroutine_handle<> next; + try + { + next = p.wg_.executor().dispatch(std::move(task_chain)); + } + catch(...) + { + std::ignore = task_chain.release_handle(); + throw; + } // From here the trampoline destroys itself when the task ends. tr_.h_ = nullptr; next.resume(); diff --git a/include/boost/capy/ex/strand.hpp b/include/boost/capy/ex/strand.hpp index a67091f4c..5b65d40d7 100644 --- a/include/boost/capy/ex/strand.hpp +++ b/include/boost/capy/ex/strand.hpp @@ -12,11 +12,12 @@ #define BOOST_CAPY_EX_STRAND_HPP #include -#include +#include #include #include #include +#include namespace boost { namespace capy { @@ -246,16 +247,16 @@ class strand it is dequeued and resumed. */ void - post(continuation& c) const + post(coro_chain&& c) const { - detail::strand_service::post(impl_, executor_ref(ex_), c); + detail::strand_service::post(impl_, executor_ref(ex_), std::move(c)); } /** Dispatch a continuation through the strand. Returns a handle for symmetric transfer. If the calling - thread is already executing within this strand, returns `c.h`. - Otherwise, the continuation is queued and + thread is already executing within this strand, returns the + leaf handle. Otherwise, the chain is queued and `std::noop_coroutine()` is returned. @pre The strand's execution context must outlive this call. @@ -272,16 +273,14 @@ class strand @throws std::bad_alloc If allocation fails. @throws Any exception thrown by the inner executor's `post`. - @param c The continuation to dispatch. The caller retains - ownership; the continuation must remain valid until - it is dequeued and resumed. + @param c The chain to dispatch. @return A handle for symmetric transfer or `std::noop_coroutine()`. */ std::coroutine_handle<> - dispatch(continuation& c) const + dispatch(coro_chain&& c) const { - return detail::strand_service::dispatch(impl_, executor_ref(ex_), c); + return detail::strand_service::dispatch(impl_, executor_ref(ex_), std::move(c)); } }; diff --git a/include/boost/capy/ex/thread_pool.hpp b/include/boost/capy/ex/thread_pool.hpp index 477d09c17..ac649b0d8 100644 --- a/include/boost/capy/ex/thread_pool.hpp +++ b/include/boost/capy/ex/thread_pool.hpp @@ -12,7 +12,7 @@ #define BOOST_CAPY_EX_THREAD_POOL_HPP #include -#include +#include #include #include #include @@ -283,7 +283,7 @@ class thread_pool::executor_type */ BOOST_CAPY_DECL std::coroutine_handle<> - dispatch(continuation& c) const; + dispatch(coro_chain&& c) const; /** Post a continuation to the thread pool. @@ -299,9 +299,6 @@ class thread_pool::executor_type thread can therefore go either way, and nothing in the call tells the caller which. - The continuation must remain at a stable address until it - is resumed or abandoned. - @param c The continuation to execute. @throws std::system_error If this call must start the pool's @@ -312,7 +309,7 @@ class thread_pool::executor_type */ BOOST_CAPY_DECL void - post(continuation& c) const; + post(coro_chain&& c) const; /** Return true if two executors refer to the same thread pool. diff --git a/include/boost/capy/io/write_now.hpp b/include/boost/capy/io/write_now.hpp index 7a542c692..2a43a8819 100644 --- a/include/boost/capy/io/write_now.hpp +++ b/include/boost/capy/io/write_now.hpp @@ -20,7 +20,6 @@ #include #include #include -#include #include #include @@ -247,7 +246,7 @@ class write_now // that is still awaited. auto& p = h_.promise(); if(!p.done_ && p.owner_ && - !(p.env_->owner && p.env_->owner->abandoned())) + !p.env_->is_unwinding()) std::terminate(); // LCOV_EXCL_LINE reached only in a death test's child process h_.destroy(); } diff --git a/include/boost/capy/task.hpp b/include/boost/capy/task.hpp index f8c19eabd..5e342cbae 100644 --- a/include/boost/capy/task.hpp +++ b/include/boost/capy/task.hpp @@ -327,7 +327,7 @@ struct [[nodiscard]] BOOST_CAPY_CORO_AWAIT_ELIDABLE [[nodiscard]] auto await_resume() requires detail::is_results_v { - lent_ = false; + h_.promise().set_lent(false); if(h_.promise().has_ep_) std::rethrow_exception(h_.promise().ep_); return std::move(*h_.promise().result_); @@ -346,7 +346,7 @@ struct [[nodiscard]] BOOST_CAPY_CORO_AWAIT_ELIDABLE auto await_resume() requires (! detail::is_results_v) { - lent_ = false; + h_.promise().set_lent(false); if(h_.promise().has_ep_) std::rethrow_exception(h_.promise().ep_); if constexpr (! std::is_void_v) @@ -374,7 +374,7 @@ struct [[nodiscard]] BOOST_CAPY_CORO_AWAIT_ELIDABLE { h_.promise().set_continuation(cont); h_.promise().set_environment(env); - lent_ = true; + h_.promise().set_lent(true); return h_; } @@ -477,9 +477,6 @@ struct [[nodiscard]] BOOST_CAPY_CORO_AWAIT_ELIDABLE } private: - // Set while a parent is suspended awaiting this task. - bool lent_ = false; - explicit task(std::coroutine_handle h) : h_(h) { @@ -487,18 +484,7 @@ struct [[nodiscard]] BOOST_CAPY_CORO_AWAIT_ELIDABLE void destroy_frame() noexcept { - if(!h_) - return; - if(lent_ && !h_.done()) - { - // Only the unwind of an abandoned chain destroys a frame - // that is still awaited. - auto* owner = h_.promise().environment()->owner; - if(!owner || !owner->abandoned()) - std::terminate(); // LCOV_EXCL_LINE reached only in a death test's child process - } - std::exchange(h_, nullptr).destroy(); - lent_ = false; + promise_type::destroy_coro(std::exchange(h_, nullptr)); } }; diff --git a/include/boost/capy/test/run_blocking.hpp b/include/boost/capy/test/run_blocking.hpp index 8f53a4b1b..824c7312a 100644 --- a/include/boost/capy/test/run_blocking.hpp +++ b/include/boost/capy/test/run_blocking.hpp @@ -96,18 +96,18 @@ struct BOOST_CAPY_DECL blocking_executor `std::noop_coroutine()` if the continuation was queued. */ std::coroutine_handle<> - dispatch(continuation& c) const; + dispatch(coro_chain&& c) const; /** Post work for deferred execution. - Enqueues the coroutine handle into the context's work - queue. The handle is resumed when the blocking event + Enqueues the coroutine chain into the context's work + queue. The chain is resumed when the blocking event loop processes it. - @param c The continuation to enqueue. + @param c The chain to enqueue. */ void - post(continuation& c) const; + post(coro_chain&& c) const; private: blocking_context* ctx_; @@ -210,7 +210,7 @@ class BOOST_CAPY_DECL blocking_context @param c The continuation to enqueue. */ void - enqueue(continuation const& c); + enqueue(coro_chain&& c); }; /** Forward a task's outcome to its handlers, then signal the blocking context. diff --git a/include/boost/capy/test/stream.hpp b/include/boost/capy/test/stream.hpp index 9e7ef1729..0b6844db9 100644 --- a/include/boost/capy/test/stream.hpp +++ b/include/boost/capy/test/stream.hpp @@ -15,7 +15,7 @@ #include #include #include -#include +#include #include #include #include @@ -77,9 +77,7 @@ class stream { std::string buf; std::size_t max_read_size = std::size_t(-1); - // The parked read's own continuation: an executor may queue it - // in place, so it is never copied or changed once posted. - continuation* pending_cont_ = nullptr; + coro_chain* pending_chain_ = nullptr; executor_ref pending_ex; // Points at the suspended reader's claim flag (owned by the // read awaitable). Lets a peer wake coordinate with a stop @@ -104,7 +102,7 @@ class stream // stop callback; the loser of the race skips the post. static void wake(half& side) { - auto* c = std::exchange(side.pending_cont_, nullptr); + auto* c = std::exchange(side.pending_chain_, nullptr); if(! c) return; auto ex = std::exchange(side.pending_ex, {}); @@ -112,7 +110,7 @@ class stream if(! claimed || ! claimed->exchange(true, std::memory_order_acq_rel)) { - ex.post(*c); + ex.post(std::move(*c)); } } @@ -270,7 +268,7 @@ class stream // Declared before stop_cb_buf_: the stop callback reads // these, so they must outlive a blocking stop_cb_ destructor. - continuation cont_; + coro_chain chain_; executor_ref ex_; half* side_ = nullptr; std::atomic claimed_{false}; @@ -287,7 +285,7 @@ class stream true, std::memory_order_acq_rel)) { self_->canceled_ = true; - self_->ex_.post(self_->cont_); + self_->ex_.post(std::move(self_->chain_)); } } }; @@ -313,7 +311,7 @@ class stream awaitable(awaitable&& o) noexcept : self_(o.self_) , buffers_(o.buffers_) - , cont_(o.cont_) + , chain_(std::move(o.chain_)) , ex_(o.ex_) , side_(o.side_) , claimed_(o.claimed_.load(std::memory_order_relaxed)) @@ -331,10 +329,11 @@ class stream // peer wake does not dereference a freed claim flag. if(side_ && side_->pending_claimed == &claimed_) { - side_->pending_cont_ = nullptr; + side_->pending_chain_ = nullptr; side_->pending_ex = {}; side_->pending_claimed = nullptr; } + std::ignore = chain_.release_handle(); } awaitable(awaitable const&) = delete; @@ -365,11 +364,10 @@ class stream } auto& side = self_->state_->sides[ self_->index_]; - cont_.h = h; - cont_.owner = env->owner; + chain_ = env->park(h); ex_ = env->executor; side_ = &side; - side.pending_cont_ = &cont_; + side.pending_chain_ = &chain_; side.pending_ex = env->executor; side.pending_claimed = &claimed_; @@ -398,7 +396,7 @@ class stream // untouched; unlink if a peer wake has not already. if(side_ && side_->pending_claimed == &claimed_) { - side_->pending_cont_ = nullptr; + side_->pending_chain_ = nullptr; side_->pending_ex = {}; side_->pending_claimed = nullptr; } diff --git a/include/boost/capy/when_all.hpp b/include/boost/capy/when_all.hpp index c81e6a53c..8cb4f3de4 100644 --- a/include/boost/capy/when_all.hpp +++ b/include/boost/capy/when_all.hpp @@ -13,11 +13,10 @@ #include #include -#include +#include #include #include #include -#include #include #include #include @@ -95,7 +94,7 @@ struct when_all_core using stop_callback_t = std::stop_callback; std::optional parent_stop_callback_; - continuation continuation_; + coro_chain parent_; await_context const* caller_env_ = nullptr; // Set when a branch is abandoned before finishing: the parent is @@ -109,8 +108,8 @@ struct when_all_core stop_source_.request_stop(); if(remaining_count_.fetch_sub(1, std::memory_order_acq_rel) == 1) { - auto parent = continuation_; - capy::abandon(parent); + auto parent = std::move(parent_); + parent.reset(); } } @@ -140,7 +139,6 @@ struct when_all_state when_all_core core_; std::tuple...> results_; - std::array runner_handles_{}; std::atomic has_error_{false}; std::error_code first_error_; @@ -172,7 +170,6 @@ struct when_all_homogeneous_state { when_all_core core_; std::vector> results_; - std::unique_ptr runner_handles_; std::atomic has_error_{false}; std::error_code first_error_; @@ -180,7 +177,6 @@ struct when_all_homogeneous_state explicit when_all_homogeneous_state(std::size_t count) : core_(count) , results_(count) - , runner_handles_(std::make_unique(count)) { } @@ -204,14 +200,12 @@ template<> struct when_all_homogeneous_state> { when_all_core core_; - std::unique_ptr runner_handles_; std::atomic has_error_{false}; std::error_code first_error_; explicit when_all_homogeneous_state(std::size_t count) : core_(count) - , runner_handles_(std::make_unique(count)) { } @@ -243,7 +237,7 @@ struct when_all_runner std::size_t index_ = 0; await_context env_; // Owns the branch's segment. - chain_owner segment_; + chain_state chain_; bool done_ = false; ~promise_type() @@ -275,13 +269,13 @@ struct when_all_runner auto* counter = &core.remaining_count_; auto* lost = &core.lost_; auto* caller_env = core.caller_env_; - auto& cont = core.continuation_; + auto& parent = core.parent_; p_->done_ = true; // Resumed to unwind its abandoned branch: lost, not // finished. Stop is requested while this branch // still holds its share. - if(p_->segment_.abandoned()) + if(p_->chain_.abandoned()) { lost->store(true, std::memory_order_relaxed); core.stop_source_.request_stop(); @@ -293,11 +287,11 @@ struct when_all_runner return detail::symmetric_transfer(std::noop_coroutine()); if(lost->load(std::memory_order_relaxed)) { - auto parent = cont; - capy::abandon(parent); + auto p = std::move(parent); + p.reset(); return detail::symmetric_transfer(std::noop_coroutine()); } - return detail::symmetric_transfer(caller_env->executor.dispatch(cont)); + return detail::symmetric_transfer(caller_env->executor.dispatch(std::move(parent))); } void await_resume() const noexcept {} // LCOV_EXCL_LINE final_suspend awaiter, never resumed }; @@ -317,11 +311,39 @@ struct when_all_runner template struct transform_awaiter { - std::decay_t a_; + Awaitable& a_; promise_type* p_; - bool await_ready() { return a_.await_ready(); } - decltype(auto) await_resume() { return a_.await_resume(); } + bool await_ready() + { + p_->chain_.bind( + std::coroutine_handle::from_promise(*p_), + p_->env_.executor, + p_->env_.frame_allocator); + return a_.await_ready(); + } + + auto await_resume() + { +#ifndef NDEBUG + BOOST_CAPY_ASSERT(!p_->env_.is_parked()); +#endif + using R = decltype(a_.await_resume()); + bool const unwinding = p_->chain_.abandoned(); + if constexpr (std::is_void_v) + { + if(unwinding) + return false; + a_.await_resume(); + return true; + } + else + { + if(unwinding) + return std::optional(); + return std::optional(a_.await_resume()); + } + } template auto await_suspend(std::coroutine_handle h) @@ -340,8 +362,7 @@ struct when_all_runner using A = std::decay_t; if constexpr (ContextAwaitable) { - return transform_awaiter{ - std::forward(a), this}; + return transform_awaiter{a, this}; } else { @@ -386,7 +407,7 @@ make_when_all_homogeneous_runner(Awaitable* inner, StateType* state, std::size_t // a runner destroyed unstarted owns no branch, and one destroyed // unfinished destroys it before its promise reports the loss. Awaitable a(std::move(*inner)); - auto r = co_await abandonable{a}; + auto r = co_await a; if(!r) co_return; auto& result = *r; @@ -417,7 +438,7 @@ make_when_all_results_runner(Awaitable* inner, when_all_state* state) // a runner destroyed unstarted owns no branch, and one destroyed // unfinished destroys it before its promise reports the loss. Awaitable a(std::move(*inner)); - auto r = co_await abandonable{a}; + auto r = co_await a; if(!r) co_return; auto ec = std::get<0>(*r); @@ -456,8 +477,7 @@ class when_all_results_launcher std::coroutine_handle<> await_suspend( std::coroutine_handle<> continuation, await_context const* caller_env) { - state_->core_.continuation_.h = continuation; - state_->core_.continuation_.owner = caller_env->owner; + state_->core_.parent_ = caller_env->park(continuation); state_->core_.caller_env_ = caller_env; if(caller_env->stop_token.stop_possible()) @@ -494,14 +514,15 @@ class when_all_results_launcher &std::get(*awaitables_), state_); auto h = runner.release(); - h.promise().state_ = state_; - h.promise().segment_.bind(h, caller_ex); - h.promise().env_ = await_context{caller_ex, token, + auto& rp = h.promise(); + rp.state_ = state_; + rp.env_ = await_context{caller_ex, token, state_->core_.caller_env_->frame_allocator, - &h.promise().segment_}; + &rp.chain_}; + rp.chain_.bind_root(h); + rp.chain_.arm_root(); - state_->runner_handles_[I].h = std::coroutine_handle<>{h}; - state_->core_.caller_env_->executor.post(state_->runner_handles_[I]); + state_->core_.caller_env_->executor.post(coro_chain::from_address(&rp.chain_)); } }; @@ -559,8 +580,7 @@ class when_all_homogeneous_launcher std::coroutine_handle<> await_suspend(std::coroutine_handle<> continuation, await_context const* caller_env) { - state_->core_.continuation_.h = continuation; - state_->core_.continuation_.owner = caller_env->owner; + state_->core_.parent_ = caller_env->park(continuation); state_->core_.caller_env_ = caller_env; if(caller_env->stop_token.stop_possible()) @@ -576,6 +596,7 @@ class when_all_homogeneous_launcher auto token = state_->core_.stop_source_.get_token(); // Phase 1: Create all runners without dispatching. + chain_queue pending; std::size_t index = 0; for(auto&& a : *range_) { @@ -583,22 +604,23 @@ class when_all_homogeneous_launcher &a, state_, index); auto h = runner.release(); - h.promise().state_ = state_; - h.promise().index_ = index; - h.promise().segment_.bind(h, caller_env->executor); - h.promise().env_ = await_context{caller_env->executor, token, - caller_env->frame_allocator, &h.promise().segment_}; - - state_->runner_handles_[index].h = std::coroutine_handle<>{h}; + auto& rp = h.promise(); + rp.state_ = state_; + rp.index_ = index; + rp.env_ = await_context{caller_env->executor, token, + caller_env->frame_allocator, &rp.chain_}; + rp.chain_.bind_root(h); + rp.chain_.arm_root(); + + pending.push(coro_chain::from_address(&rp.chain_)); ++index; } // Phase 2: Post all runners. Any may complete synchronously. // After last post, state_ and this may be destroyed. - auto* handles = state_->runner_handles_.get(); - std::size_t count = state_->core_.remaining_count_.load(std::memory_order_relaxed); - for(std::size_t i = 0; i < count; ++i) - caller_env->executor.post(handles[i]); + auto ex = caller_env->executor; + while(auto c = pending.pop()) + ex.post(std::move(c)); return std::noop_coroutine(); } diff --git a/include/boost/capy/when_any.hpp b/include/boost/capy/when_any.hpp index 45065bb2a..ff3a899a2 100644 --- a/include/boost/capy/when_any.hpp +++ b/include/boost/capy/when_any.hpp @@ -13,12 +13,11 @@ #include #include -#include +#include #include #include #include #include -#include #include #include #include @@ -153,7 +152,7 @@ struct when_any_core using stop_callback_t = std::stop_callback; std::optional parent_stop_callback_; - continuation continuation_; + coro_chain parent_; await_context const* caller_env_ = nullptr; // Set when a branch is abandoned before finishing: the parent is @@ -167,8 +166,8 @@ struct when_any_core stop_source_.request_stop(); if(remaining_count_.fetch_sub(1, std::memory_order_acq_rel) == 1) { - auto parent = continuation_; - capy::abandon(parent); + auto parent = std::move(parent_); + parent.reset(); } } @@ -216,7 +215,6 @@ struct when_any_results_state when_any_core core_; std::optional result_; - std::array runner_handles_{}; // A failure (error or exception) for the all-fail case. record_error // and record_exception overwrite each other, so which one survives is @@ -257,7 +255,7 @@ struct when_any_results_runner std::size_t index_ = 0; await_context env_; // Owns the branch's segment. - chain_owner segment_; + chain_state chain_; bool done_ = false; ~promise_type() @@ -286,13 +284,13 @@ struct when_any_results_runner auto* counter = &core.remaining_count_; auto* lost = &core.lost_; auto* caller_env = core.caller_env_; - auto& cont = core.continuation_; + auto& parent = core.parent_; p_->done_ = true; // Resumed to unwind its abandoned branch: lost, not // finished. Stop is requested while this branch // still holds its share. - if(p_->segment_.abandoned()) + if(p_->chain_.abandoned()) { lost->store(true, std::memory_order_relaxed); core.stop_source_.request_stop(); @@ -304,11 +302,11 @@ struct when_any_results_runner return detail::symmetric_transfer(std::noop_coroutine()); if(lost->load(std::memory_order_relaxed)) { - auto parent = cont; - capy::abandon(parent); + auto p = std::move(parent); + p.reset(); return detail::symmetric_transfer(std::noop_coroutine()); } - return detail::symmetric_transfer(caller_env->executor.dispatch(cont)); + return detail::symmetric_transfer(caller_env->executor.dispatch(std::move(parent))); } void await_resume() const noexcept {} // LCOV_EXCL_LINE final_suspend awaiter, never resumed }; @@ -328,11 +326,39 @@ struct when_any_results_runner template struct transform_awaiter { - std::decay_t a_; + Awaitable& a_; promise_type* p_; - bool await_ready() { return a_.await_ready(); } - decltype(auto) await_resume() { return a_.await_resume(); } + bool await_ready() + { + p_->chain_.bind( + std::coroutine_handle::from_promise(*p_), + p_->env_.executor, + p_->env_.frame_allocator); + return a_.await_ready(); + } + + auto await_resume() + { +#ifndef NDEBUG + BOOST_CAPY_ASSERT(!p_->env_.is_parked()); +#endif + using R = decltype(a_.await_resume()); + bool const unwinding = p_->chain_.abandoned(); + if constexpr (std::is_void_v) + { + if(unwinding) + return false; + a_.await_resume(); + return true; + } + else + { + if(unwinding) + return std::optional(); + return std::optional(a_.await_resume()); + } + } template auto await_suspend(std::coroutine_handle h) @@ -351,8 +377,7 @@ struct when_any_results_runner using A = std::decay_t; if constexpr (ContextAwaitable) { - return transform_awaiter{ - std::forward(a), this}; + return transform_awaiter{a, this}; } else { @@ -392,7 +417,7 @@ make_when_any_results_runner(Awaitable* inner, StateType* state) // a runner destroyed unstarted owns no branch, and one destroyed // unfinished destroys it before its promise reports the loss. Awaitable a(std::move(*inner)); - auto r = co_await abandonable{a}; + auto r = co_await a; if(!r) co_return; auto& result = *r; @@ -448,8 +473,7 @@ class when_any_results_launcher std::coroutine_handle<> await_suspend( std::coroutine_handle<> continuation, await_context const* caller_env) { - state_->core_.continuation_.h = continuation; - state_->core_.continuation_.owner = caller_env->owner; + state_->core_.parent_ = caller_env->park(continuation); state_->core_.caller_env_ = caller_env; if(caller_env->stop_token.stop_possible()) @@ -486,15 +510,16 @@ class when_any_results_launcher &std::get(*tasks_), state_); auto h = runner.release(); - h.promise().state_ = state_; - h.promise().index_ = I; - h.promise().segment_.bind(h, caller_ex); - h.promise().env_ = await_context{caller_ex, token, + auto& rp = h.promise(); + rp.state_ = state_; + rp.index_ = I; + rp.env_ = await_context{caller_ex, token, state_->core_.caller_env_->frame_allocator, - &h.promise().segment_}; + &rp.chain_}; + rp.chain_.bind_root(h); + rp.chain_.arm_root(); - state_->runner_handles_[I].h = std::coroutine_handle<>{h}; - caller_ex.post(state_->runner_handles_[I]); + caller_ex.post(coro_chain::from_address(&rp.chain_)); } }; @@ -507,7 +532,6 @@ struct when_any_results_homogeneous_state { when_any_core core_; std::optional result_; - std::unique_ptr runner_handles_; std::mutex failure_mu_; std::error_code last_error_; @@ -515,7 +539,6 @@ struct when_any_results_homogeneous_state explicit when_any_results_homogeneous_state(std::size_t count) : core_(count) - , runner_handles_(std::make_unique(count)) { } @@ -539,7 +562,6 @@ template<> struct when_any_results_homogeneous_state> { when_any_core core_; - std::unique_ptr runner_handles_; std::mutex failure_mu_; std::error_code last_error_; @@ -547,7 +569,6 @@ struct when_any_results_homogeneous_state> explicit when_any_results_homogeneous_state(std::size_t count) : core_(count) - , runner_handles_(std::make_unique(count)) { } @@ -579,7 +600,7 @@ make_when_any_results_homogeneous_runner( // a runner destroyed unstarted owns no branch, and one destroyed // unfinished destroys it before its promise reports the loss. Awaitable a(std::move(*inner)); - auto r = co_await abandonable{a}; + auto r = co_await a; if(!r) co_return; auto& result = *r; @@ -638,8 +659,7 @@ class when_any_results_homogeneous_launcher std::coroutine_handle<> await_suspend( std::coroutine_handle<> continuation, await_context const* caller_env) { - state_->core_.continuation_.h = continuation; - state_->core_.continuation_.owner = caller_env->owner; + state_->core_.parent_ = caller_env->park(continuation); state_->core_.caller_env_ = caller_env; if(caller_env->stop_token.stop_possible()) @@ -655,6 +675,7 @@ class when_any_results_homogeneous_launcher auto token = state_->core_.stop_source_.get_token(); // Phase 1: Create all runners without dispatching. + chain_queue pending; std::size_t index = 0; for(auto&& a : *range_) { @@ -662,21 +683,22 @@ class when_any_results_homogeneous_launcher &a, state_, index); auto h = runner.release(); - h.promise().state_ = state_; - h.promise().index_ = index; - h.promise().segment_.bind(h, caller_env->executor); - h.promise().env_ = await_context{caller_env->executor, token, - caller_env->frame_allocator, &h.promise().segment_}; - - state_->runner_handles_[index].h = std::coroutine_handle<>{h}; + auto& rp = h.promise(); + rp.state_ = state_; + rp.index_ = index; + rp.env_ = await_context{caller_env->executor, token, + caller_env->frame_allocator, &rp.chain_}; + rp.chain_.bind_root(h); + rp.chain_.arm_root(); + + pending.push(coro_chain::from_address(&rp.chain_)); ++index; } // Phase 2: Post all runners. Any may complete synchronously. - auto* handles = state_->runner_handles_.get(); - std::size_t count = state_->core_.remaining_count_.load(std::memory_order_relaxed); - for(std::size_t i = 0; i < count; ++i) - caller_env->executor.post(handles[i]); + auto ex = caller_env->executor; + while(auto c = pending.pop()) + ex.post(std::move(c)); return std::noop_coroutine(); } diff --git a/src/ex/detail/strand_queue.hpp b/src/ex/detail/strand_queue.hpp index d34106844..d96d66d74 100644 --- a/src/ex/detail/strand_queue.hpp +++ b/src/ex/detail/strand_queue.hpp @@ -11,10 +11,8 @@ #ifndef BOOST_CAPY_SRC_EX_DETAIL_STRAND_QUEUE_HPP #define BOOST_CAPY_SRC_EX_DETAIL_STRAND_QUEUE_HPP -#include +#include #include -#include -#include #include @@ -22,135 +20,58 @@ namespace boost { namespace capy { namespace detail { -/** Single-threaded intrusive FIFO of pending continuations. +/** Single-threaded intrusive FIFO of pending `coro_chain` items. - Links continuations directly through `continuation::reserved` (a - typed `continuation*` round-tripped through the `void*` slot), so - push() carries no per-item allocation. - - @par Thread Safety - Not thread-safe. Caller must externally synchronize push() and - take_all(). dispatch_batch() does not touch queue state and may - run unlocked once the batch has been taken. + Wraps @ref chain_queue for strand batching and withdrawal. */ class strand_queue { - continuation* head_ = nullptr; - continuation* tail_ = nullptr; + chain_queue q_; public: + using taken_batch = chain_queue; + strand_queue() = default; strand_queue(strand_queue const&) = delete; strand_queue& operator=(strand_queue const&) = delete; - /** Returns true if there are no pending continuations. */ bool empty() const noexcept { - return head_ == nullptr; + return q_.empty(); } - /** Push a continuation to the queue. - - @param c The continuation to enqueue; see `continuation` - for lifetime and aliasing requirements. - */ void - push(continuation& c) noexcept + push(coro_chain&& c) noexcept { - c.reserved = nullptr; - if(tail_) - tail_->reserved = &c; - else - head_ = &c; - tail_ = &c; + q_.push(std::move(c)); } - /// Return the first pending continuation, or null if empty. - continuation* - front() const noexcept - { - return head_; - } - - /** Remove the first pending continuation. - - @pre The queue is not empty. - */ - void + coro_chain pop_front() noexcept { - head_ = static_cast(head_->reserved); - if(!head_) - tail_ = nullptr; + return q_.pop(); } - /** Batch of taken items for thread-safe dispatch. */ - struct taken_batch - { - continuation* head = nullptr; - continuation* tail = nullptr; - }; - - /** Take all pending items atomically. - - Removes all items from the queue and returns them as a - batch. The queue is left empty. - - @return The batch of taken items. - */ taken_batch take_all() noexcept { - taken_batch batch{head_, tail_}; - head_ = tail_ = nullptr; - return batch; + return std::move(q_); } - /** Resume each continuation in a taken batch. - - Advances past each node before resuming, since the - resumed coroutine may destroy the awaitable (and thus - the continuation) before control returns here. - - @param batch The batch to dispatch. - - @note Thread-safe with respect to push() because the queue - itself is not touched. - */ static void dispatch_batch(taken_batch& batch) { - while(batch.head) - { - continuation* c = batch.head; - batch.head = static_cast(c->reserved); - safe_resume(c->h); - } - batch.tail = nullptr; + while(auto c = batch.pop()) + c.resume(); } - /** Abandon each coroutine in a taken batch without resuming it. - - Used when the strand can no longer run them. Advances past - each node first, since the node may live in a frame the - abandon destroys. - - @param batch The batch to abandon. - */ static void abandon_batch(taken_batch& batch) noexcept { - while(batch.head) - { - continuation* c = batch.head; - batch.head = static_cast(c->reserved); - if(c->h) - capy::abandon(*c); - } - batch.tail = nullptr; + batch.clear(); } }; diff --git a/src/ex/detail/strand_service.cpp b/src/ex/detail/strand_service.cpp index 96dc9d78e..98b1267b8 100644 --- a/src/ex/detail/strand_service.cpp +++ b/src/ex/detail/strand_service.cpp @@ -9,7 +9,7 @@ #include "src/ex/detail/strand_impl.hpp" #include -#include +#include #include #include #include @@ -82,7 +82,7 @@ class strand_service_impl : public strand_service // Returns the service when the caller must post an invoker. static strand_service_impl* - enqueue(strand_impl& impl, continuation& c) + enqueue(strand_impl& impl, coro_chain&& c) { // A closed strand never locks: the mutex it borrowed may have // gone with its service. @@ -91,7 +91,7 @@ class strand_service_impl : public strand_service std::lock_guard lock(*impl.mutex_); if(auto* svc = impl.service_.load(std::memory_order_relaxed)) { - impl.pending_.push(c); + impl.pending_.push(std::move(c)); if(!impl.locked_) { impl.locked_ = true; @@ -100,8 +100,8 @@ class strand_service_impl : public strand_service return nullptr; } } - // Shut down: nothing will run it, so abandon it as its holder. - capy::abandon(c); + // Shut down: nothing will run it, so unwind it as its holder. + c.reset(); return nullptr; } @@ -112,20 +112,19 @@ class strand_service_impl : public strand_service taken }; - // Takes back a continuation whose invoker could not be posted. + // Takes back a chain whose invoker could not be posted. // `taken` means a shutdown took it first and abandoned it. static withdrawal - withdraw(strand_impl& impl, continuation& c) noexcept + withdraw(strand_impl& impl, coro_chain& out) noexcept { std::lock_guard lock(*impl.mutex_); if(!impl.service_.load(std::memory_order_relaxed)) return withdrawal::taken; // Nothing takes from the queue while it waits for an invoker, - // so `c` is still first. - BOOST_CAPY_ASSERT(impl.pending_.front() == &c); - std::ignore = c; - impl.pending_.pop_front(); - // Posts queued behind `c` returned trusting its invoker, so + // so the item is still first. + out = impl.pending_.pop_front(); + BOOST_CAPY_ASSERT(static_cast(out)); + // Posts queued behind `out` returned trusting its invoker, so // the strand stays locked until one runs them. if(!impl.pending_.empty()) return withdrawal::followed; @@ -203,15 +202,7 @@ class strand_service_impl : public strand_service std::lock_guard impl_lock(*p->mutex_); p->locked_ = true; p->service_.store(nullptr, std::memory_order_release); - auto b = p->pending_.take_all(); - if(b.head) - { - if(doomed.tail) - doomed.tail->reserved = b.head; - else - doomed.head = b.head; - doomed.tail = b.tail; - } + doomed.splice(p->pending_.take_all()); } } // Outside the mutexes: a destroyed frame may drop the last @@ -242,7 +233,7 @@ struct strand_invoker { // Stored in the coroutine frame so its address is stable for // posting to the inner executor. - continuation self_; + chain_state self_; // The service is the one enqueue() saw under the strand's lock; // the impl's own pointer may be cleared by a concurrent shutdown. @@ -330,14 +321,17 @@ strand_service_impl::post_invoker( { auto invoker = make_invoker(svc, std::move(impl)); auto& self = invoker.h_.promise().self_; - self.h = invoker.h_; + self.bind_root(invoker.h_); + self.arm_root(); + coro_chain c = coro_chain::from_address(&self); try { - ex.post(self); + ex.post(std::move(c)); } catch(...) { - invoker.h_.destroy(); + // If ex.post threw before taking ownership, c is still armed + // and its destructor destroys invoker.h_. throw; } } @@ -350,7 +344,7 @@ post_or_withdraw( strand_service_impl* svc, std::shared_ptr const& impl, executor_ref ex, - continuation& c) + coro_chain& caller_c) { try { @@ -359,7 +353,7 @@ post_or_withdraw( catch(...) { using withdrawal = strand_service_impl::withdrawal; - auto const w = strand_service_impl::withdraw(*impl, c); + auto const w = strand_service_impl::withdraw(*impl, caller_c); if(w == withdrawal::taken) return; if(w == withdrawal::followed) @@ -410,12 +404,12 @@ strand_service:: dispatch( std::shared_ptr const& impl, executor_ref ex, - continuation& c) + coro_chain&& c) { if(running_in_this_thread(*impl)) - return c.h; + return c.release_handle(); - if(auto* svc = strand_service_impl::enqueue(*impl, c)) + if(auto* svc = strand_service_impl::enqueue(*impl, std::move(c))) post_or_withdraw(svc, impl, ex, c); return std::noop_coroutine(); } @@ -425,9 +419,9 @@ strand_service:: post( std::shared_ptr const& impl, executor_ref ex, - continuation& c) + coro_chain&& c) { - if(auto* svc = strand_service_impl::enqueue(*impl, c)) + if(auto* svc = strand_service_impl::enqueue(*impl, std::move(c))) post_or_withdraw(svc, impl, ex, c); } diff --git a/src/ex/thread_pool.cpp b/src/ex/thread_pool.cpp index 9d756584e..e11b4abab 100644 --- a/src/ex/thread_pool.cpp +++ b/src/ex/thread_pool.cpp @@ -9,9 +9,8 @@ // #include -#include +#include #include -#include #include #include #include @@ -20,6 +19,7 @@ #include #include #include +#include #include /* @@ -63,36 +63,21 @@ class thread_pool::impl // resume) and post. static inline detail::thread_local_ptr current_; - // Intrusive queue of continuations: the next link is stored in - // continuation::reserved (typed continuation* round-tripped through - // void*). No per-post allocation: the continuation is owned by the caller. - continuation* head_ = nullptr; - continuation* tail_ = nullptr; + chain_queue queue_; - void push(continuation* c) noexcept + void push(coro_chain&& c) noexcept { - c->reserved = nullptr; - if(tail_) - tail_->reserved = c; - else - head_ = c; - tail_ = c; + queue_.push(std::move(c)); } - continuation* pop() noexcept + coro_chain pop() noexcept { - if(!head_) - return nullptr; - continuation* c = head_; - head_ = static_cast(head_->reserved); - if(!head_) - tail_ = nullptr; - return c; + return queue_.pop(); } bool empty() const noexcept { - return head_ == nullptr; + return queue_.empty(); } std::mutex mutex_; @@ -123,15 +108,17 @@ class thread_pool::impl { for(;;) { - continuation* c; + coro_chain c; { std::lock_guard lock(mutex_); c = pop(); } if(!c) return; - if(c->h && c->h != std::noop_coroutine()) - capy::abandon(*c); + if(c.handle() == std::noop_coroutine()) + std::ignore = c.release_handle(); + else + c.reset(); } } @@ -148,7 +135,7 @@ class thread_pool::impl } void - post(continuation& c) + post(coro_chain&& c) { if(!started_.load(std::memory_order_acquire)) { @@ -158,14 +145,14 @@ class thread_pool::impl { // Stopped before any thread started: nothing will // run it, and the destructor's drain abandons it. - push(&c); + push(std::move(c)); return; } } ensure_started(); } std::lock_guard lock(mutex_); - push(&c); + push(std::move(c)); // Under the lock so the pool cannot drain, join, and // destroy the condition variable mid-signal. work_cv_.notify_one(); @@ -274,7 +261,7 @@ class thread_pool::impl for(;;) { - continuation* c = nullptr; + coro_chain c; { std::unique_lock lock(mutex_); work_cv_.wait(lock, [this]{ @@ -286,7 +273,7 @@ class thread_pool::impl c = pop(); } if(c) - safe_resume(c->h); + c.resume(); } } }; @@ -299,12 +286,8 @@ thread_pool:: impl_->stop(); impl_->join(); shutdown(); - // Takes what the unwinds post too, and the work of any service they - // create, which is shut down as it is created. impl_->drain_abandoned(); destroy(); - // Services give up their work in shutdown(), but anything a - // destructor posts anyway is still destroyed. impl_->drain_abandoned(); delete impl_; } @@ -356,18 +339,18 @@ on_work_finished() const noexcept void thread_pool::executor_type:: -post(continuation& c) const +post(coro_chain&& c) const { - pool_->impl_->post(c); + pool_->impl_->post(std::move(c)); } std::coroutine_handle<> thread_pool::executor_type:: -dispatch(continuation& c) const +dispatch(coro_chain&& c) const { if(pool_->impl_->running_in_this_thread()) - return c.h; - pool_->impl_->post(c); + return c.release_handle(); + pool_->impl_->post(std::move(c)); return std::noop_coroutine(); } diff --git a/src/test/run_blocking.cpp b/src/test/run_blocking.cpp index 88d03713a..7b5d892e0 100644 --- a/src/test/run_blocking.cpp +++ b/src/test/run_blocking.cpp @@ -9,8 +9,7 @@ #include -#include -#include +#include #include #include #include @@ -33,7 +32,7 @@ struct blocking_context::impl { std::mutex mtx; std::condition_variable cv; - std::queue queue; + std::queue queue; std::exception_ptr ep; bool done = false; bool abandoned = false; @@ -46,31 +45,24 @@ blocking_context::blocking_context() blocking_context::~blocking_context() { - // Nothing will run these now; abandon them as their holder. Each is - // taken under the lock and abandoned outside it, since abandoning - // one may post another. auto drain = [this] { for(;;) { - continuation c; + coro_chain c; { std::lock_guard lock(impl_->mtx); if(impl_->queue.empty()) return; - c = impl_->queue.front(); + c = std::move(impl_->queue.front()); impl_->queue.pop(); } - capy::abandon(c); + c.reset(); } }; shutdown(); - // Takes what the unwinds post too, and the work of any service they - // create, which is shut down as it is created. drain(); destroy(); - // Services give up their work in shutdown(), but anything a - // destructor posts anyway is still destroyed. drain(); delete impl_; } @@ -128,7 +120,7 @@ blocking_context::run() for(;;) { - continuation c; + coro_chain c; { std::unique_lock lock(impl_->mtx); impl_->cv.wait(lock, [&] { @@ -136,10 +128,10 @@ blocking_context::run() }); if(impl_->done && impl_->queue.empty()) break; - c = impl_->queue.front(); + c = std::move(impl_->queue.front()); impl_->queue.pop(); } - safe_resume(c.h); + c.resume(); } if(impl_->ep) std::rethrow_exception(impl_->ep); @@ -149,10 +141,10 @@ blocking_context::run() void blocking_context::enqueue( - continuation const& c) + coro_chain&& c) { std::lock_guard lock(impl_->mtx); - impl_->queue.push(c); + impl_->queue.push(std::move(c)); impl_->cv.notify_one(); } @@ -183,19 +175,19 @@ blocking_executor::on_work_finished() const noexcept std::coroutine_handle<> blocking_executor::dispatch( - continuation& c) const + coro_chain&& c) const { if(running_ == ctx_) - return c.h; - ctx_->enqueue(c); + return c.release_handle(); + ctx_->enqueue(std::move(c)); return std::noop_coroutine(); } void blocking_executor::post( - continuation& c) const + coro_chain&& c) const { - ctx_->enqueue(c); + ctx_->enqueue(std::move(c)); } } // namespace test diff --git a/test/unit/test_helpers.hpp b/test/unit/test_helpers.hpp index a508adfbf..6a0323244 100644 --- a/test/unit/test_helpers.hpp +++ b/test/unit/test_helpers.hpp @@ -14,7 +14,7 @@ #include #include #include -#include +#include #include #include #include @@ -109,17 +109,17 @@ struct test_executor void on_work_finished() const noexcept {} std::coroutine_handle<> - dispatch(continuation& c) const + dispatch(coro_chain&& c) const { if(dispatch_count_) ++(*dispatch_count_); - return c.h; + return c.release_handle(); } void - post(continuation& c) const + post(coro_chain&& c) const { - c.h.resume(); + c.resume(); } }; @@ -261,8 +261,7 @@ struct self_destroy_awaitable std::coroutine_handle<> await_suspend(std::coroutine_handle<> h, await_context const* env) { - continuation c{h, nullptr, env->owner}; - capy::abandon(c); + env->park(h).reset(); return std::noop_coroutine(); } void await_resume() {} @@ -276,11 +275,11 @@ struct self_destroy_awaitable struct resume_via_post { executor_ref ex; - mutable continuation cont; + mutable coro_chain chain; void operator()() const noexcept { - ex.post(cont); + ex.post(std::move(chain)); } }; @@ -291,7 +290,7 @@ post_resume( await_context const& env, std::coroutine_handle<> h) noexcept { - return resume_via_post{env.executor, continuation{h, nullptr, env.owner}}; + return resume_via_post{env.executor, env.park(h)}; } // test awaitable that must be stopped in order to resume. @@ -499,10 +498,10 @@ class stashing_range */ struct queuing_executor { - std::queue* queue_; + std::queue* queue_; test_io_context* ctx_ = nullptr; - explicit queuing_executor(std::queue& q) + explicit queuing_executor(std::queue& q) : queue_(&q) { } @@ -520,15 +519,15 @@ struct queuing_executor void on_work_started() const noexcept {} void on_work_finished() const noexcept {} - std::coroutine_handle<> dispatch(continuation& c) const + std::coroutine_handle<> dispatch(coro_chain&& c) const { - queue_->push(c); + queue_->push(std::move(c)); return std::noop_coroutine(); } - void post(continuation& c) const + void post(coro_chain&& c) const { - queue_->push(c); + queue_->push(std::move(c)); } }; @@ -541,7 +540,7 @@ static_assert(Executor); */ struct closing_executor { - std::queue* q; + std::queue* q; bool* closed; bool operator==(closing_executor const& o) const noexcept @@ -557,17 +556,17 @@ struct closing_executor void on_work_started() const noexcept {} void on_work_finished() const noexcept {} - std::coroutine_handle<> dispatch(continuation& c) const + std::coroutine_handle<> dispatch(coro_chain&& c) const { - return c.h; + return c.release_handle(); } - void post(continuation& c) const + void post(coro_chain&& c) const { if(*closed) - capy::abandon(c); + c.reset(); else - q->push(c); + q->push(std::move(c)); } }; @@ -585,8 +584,6 @@ static_assert(Executor); */ struct yield_awaitable { - continuation cont_; - bool await_ready() const noexcept { return false; @@ -595,8 +592,7 @@ struct yield_awaitable std::coroutine_handle<> await_suspend(std::coroutine_handle<> h, await_context const* env) { // Post ourselves back to the queue - cont_.h = h; - env->executor.post(cont_); + env->executor.post(env->park(h)); return std::noop_coroutine(); } @@ -622,28 +618,69 @@ struct destroy_count_t }; /** A suspended coroutine as its holder keeps it. - - Its handle, to resume it, and its segment's owner, to - @ref abandon it. */ -struct parked : continuation +struct parked { + coro_chain chain_; + std::coroutine_handle<> raw_h_{}; + + parked() = default; + parked(parked&&) = default; + parked& operator=(parked&&) = default; + + ~parked() + { + // Disarm on normal scope exit so tests that exit without + // explicitly calling reset() or resume() behave as before, + // or call reset() when explicitly testing abandonment. + std::ignore = chain_.release_handle(); + } + /// Return true while a coroutine is parked here. explicit operator bool() const noexcept { - return static_cast(h); + return static_cast(chain_) || static_cast(raw_h_); } /// Resume the parked coroutine. - void resume() const + void resume() + { + if(chain_) + { + raw_h_ = {}; + chain_.resume(); + } + else if(raw_h_) + { + std::exchange(raw_h_, nullptr).resume(); + } + } + + /// Abandon the parked coroutine chain. + void reset() noexcept + { + if(chain_) + { + raw_h_ = {}; + chain_.reset(); + } + else if(raw_h_) + { + std::exchange(raw_h_, nullptr).destroy(); + } + } + + /// Release as a coro_chain for posting to an executor. + coro_chain take() noexcept { - h.resume(); + raw_h_ = {}; + return std::move(chain_); } }; /** Parks the awaiting coroutine, handing it to the test. - The test then plays the holder: resume `*slot`, or abandon it as a + The test then plays the holder: resume `*slot`, or reset it as a context's teardown would. */ struct park_awaitable @@ -655,8 +692,8 @@ struct park_awaitable std::coroutine_handle<> await_suspend(std::coroutine_handle<> h, await_context const* env) noexcept { - slot->h = h; - slot->owner = env->owner; + slot->chain_ = env->park(h); + slot->raw_h_ = h; return std::noop_coroutine(); } @@ -807,13 +844,13 @@ struct lease /// Resume queued continuations in FIFO order until the queue is empty. inline void -pump(std::queue& q) +pump(std::queue& q) { while(!q.empty()) { - auto c = q.front(); + auto c = std::move(q.front()); q.pop(); - safe_resume(c.h); + c.resume(); } } From 169e2b68e8fd2a744490ea27614341dfc5c1904a Mon Sep 17 00:00:00 2001 From: Vinnie Falco Date: Sat, 5 Dec 2026 10:11:52 -0800 Subject: [PATCH 4/6] Update unit tests for coro_chain and verify size invariants Migrate all unit test suites under test/unit/ and test/no_rtti/ from continuation and abandon() to coro_chain, chain_state, chain_queue, frame_cb, and root_work_base. Verify 8-byte sizeof(task) and sizeof(coro_chain) invariants, preserve strong exception safety in run_async and run when dispatch/post throws, and bind when_all/when_any runner segments once running so unstarted runners destroy in place. --- include/boost/capy.hpp | 3 +- test/no_rtti/any_executor.cpp | 4 +- test/unit/ex/abandon.cpp | 90 +++--- test/unit/ex/any_executor.cpp | 46 ++- test/unit/ex/async_event.cpp | 118 ++++---- test/unit/ex/async_mutex.cpp | 166 +++++------ test/unit/ex/async_waker.cpp | 41 +-- test/unit/ex/executor_ref.cpp | 32 ++- test/unit/ex/frame_cb.cpp | 122 ++++++-- test/unit/ex/priority_executor.hpp | 82 ++---- test/unit/ex/run.cpp | 77 ++--- test/unit/ex/run_async.cpp | 55 ++-- test/unit/ex/run_blocking.cpp | 83 +++--- test/unit/ex/run_priority.cpp | 27 +- test/unit/ex/strand.cpp | 381 +++++++++++++------------ test/unit/ex/thread_pool.cpp | 154 ++++++---- test/unit/ex/work_guard.cpp | 6 +- test/unit/fault/thread_pool_faults.cpp | 36 ++- test/unit/io/any_read_stream.cpp | 11 +- test/unit/io/any_stream.cpp | 3 +- test/unit/io/any_write_stream.cpp | 9 +- test/unit/io/write_now.cpp | 10 +- test/unit/task.cpp | 37 +-- test/unit/test/stream.cpp | 13 +- test/unit/test_helpers.hpp | 24 +- test/unit/when_all.cpp | 53 ++-- test/unit/when_any.cpp | 49 ++-- 27 files changed, 944 insertions(+), 788 deletions(-) diff --git a/include/boost/capy.hpp b/include/boost/capy.hpp index 3b3975a19..05c332c19 100644 --- a/include/boost/capy.hpp +++ b/include/boost/capy.hpp @@ -52,7 +52,7 @@ #include // Execution -#include +#include #include #include #include @@ -63,6 +63,7 @@ #include #include #include +#include #include #include #include diff --git a/test/no_rtti/any_executor.cpp b/test/no_rtti/any_executor.cpp index d65bbd2d7..b01eba6e1 100644 --- a/test/no_rtti/any_executor.cpp +++ b/test/no_rtti/any_executor.cpp @@ -52,8 +52,8 @@ struct local_executor execution_context& context() const noexcept { return *ctx; } void on_work_started() const noexcept {} void on_work_finished() const noexcept {} - std::coroutine_handle<> dispatch(continuation& c) const { return c.h; } - void post(continuation&) const {} + std::coroutine_handle<> dispatch(coro_chain&& c) const { return c.release_handle(); } + void post(coro_chain&&) const {} }; using exec_a = local_executor<0>; diff --git a/test/unit/ex/abandon.cpp b/test/unit/ex/abandon.cpp index c2afb3a69..0d307d11f 100644 --- a/test/unit/ex/abandon.cpp +++ b/test/unit/ex/abandon.cpp @@ -9,7 +9,8 @@ // // Test that header file is self-contained. -#include +#include +#include #include #include @@ -43,7 +44,7 @@ namespace capy { namespace { // Parks the awaiting coroutine without the environment protocol, -// taking the owner from its promise instead. +// taking the environment from its promise instead. struct plain_park { parked* slot; @@ -53,8 +54,8 @@ struct plain_park template void await_suspend(std::coroutine_handle h) noexcept { - slot->h = h; - slot->owner = h.promise().environment()->owner; + slot->chain_ = h.promise().environment()->park(h); + slot->raw_h_ = h; } void await_resume() const noexcept {} @@ -139,8 +140,7 @@ struct own_delete_task if(h_) { auto const* env = h_.promise().environment(); - auto* owner = env ? env->owner : nullptr; - if(lent_ && !h_.done() && !(owner && owner->abandoned())) + if(lent_ && !h_.done() && !(env && env->is_unwinding())) std::terminate(); h_.destroy(); } @@ -185,10 +185,7 @@ struct holder_param ~holder_param() { if(h && *h) - { - auto c = std::exchange(*h, parked{}); - capy::abandon(c); - } + h->reset(); } }; @@ -198,13 +195,7 @@ struct holder_param */ struct parking_lot { - std::vector hs; - - ~parking_lot() - { - for(auto& c : hs) - capy::abandon(c); - } + std::vector hs; struct awaiter { @@ -215,7 +206,7 @@ struct parking_lot std::coroutine_handle<> await_suspend(std::coroutine_handle<> h, await_context const* env) { - lot->hs.push_back(continuation{h, nullptr, env->owner}); + lot->hs.push_back(env->park(h)); return std::noop_coroutine(); } @@ -258,8 +249,8 @@ struct signal_park std::coroutine_handle<> await_suspend(std::coroutine_handle<> h, await_context const* env) noexcept { - slot->h = h; - slot->owner = env->owner; + slot->chain_ = env->park(h); + slot->raw_h_ = h; done->release(); return std::noop_coroutine(); } @@ -282,13 +273,14 @@ struct counting_executor } void on_work_started() const noexcept {} void on_work_finished() const noexcept {} - std::coroutine_handle<> dispatch(continuation& c) const + std::coroutine_handle<> dispatch(coro_chain&& c) const { - post(c); + post(std::move(c)); return std::noop_coroutine(); } - void post(continuation&) const + void post(coro_chain&& c) const { + std::ignore = c.release_handle(); ++*posts; } }; @@ -298,23 +290,20 @@ struct counting_executor struct owner_root { struct promise_type - : context_awaitable_promise_base + : root_promise_base { - chain_owner owner_; - await_context env_; - template promise_type(executor_ref ex, Args&&...) - : env_{ex, {}, get_current_frame_allocator(), &owner_} { - this->set_environment(&env_); + this->bind_chain( + std::coroutine_handle::from_promise(*this), + ex, {}, get_current_frame_allocator()); } owner_root get_return_object() { auto self = std::coroutine_handle::from_promise(*this); - owner_.bind(self, env_.executor); return {self}; } std::suspend_always initial_suspend() noexcept { return {}; } @@ -357,7 +346,7 @@ owner_root wait_owned( destroy_count_t) { auto t = parked_child(slot); - auto r = co_await abandonable(t); + auto r = co_await std::move(t); if(!r) { ++*unwound; @@ -377,7 +366,7 @@ struct abandon_test constexpr int count = 1000; int inner_down = 0, outer_down = 0, server_down = 0; parked slot; - std::queue q; + std::queue q; queuing_executor ex(q); auto inner = [](parking_lot& l, destroy_count_t) -> task { @@ -403,7 +392,7 @@ struct abandon_test BOOST_TEST(slot); BOOST_TEST_EQ(inner_down, 0); - capy::abandon(slot); + slot.reset(); pump(q); BOOST_TEST_EQ(inner_down, count); BOOST_TEST_EQ(outer_down, count); @@ -436,7 +425,7 @@ struct abandon_test struct exit_holder { parked* h; - ~exit_holder() { capy::abandon(*h); } + ~exit_holder() { h->reset(); } }; thread_local exit_holder holder{&slot}; }).join(); @@ -460,7 +449,7 @@ struct abandon_test ~exit_holder() { if(h) - capy::abandon(h); + h.reset(); } }; thread_local exit_holder holder; @@ -505,7 +494,7 @@ struct abandon_test struct unwind_holder { parked* h; - ~unwind_holder() { capy::abandon(*h); } + ~unwind_holder() { h->reset(); } }; try { @@ -543,7 +532,7 @@ struct abandon_test parent(&slot, destroy_count_t(parent_down))); BOOST_TEST(slot); - capy::abandon(slot); + slot.reset(); } BOOST_TEST_EQ(child_down, 1); BOOST_TEST_EQ(parent_down, 1); @@ -585,7 +574,7 @@ struct abandon_test BOOST_TEST(slot); BOOST_TEST(other); - capy::abandon(slot); + slot.reset(); BOOST_TEST_EQ(other_down, 1); BOOST_TEST_EQ(other_parent_down, 1); BOOST_TEST_EQ(parent_down, 1); @@ -616,7 +605,7 @@ struct abandon_test if(!BOOST_TEST(done.try_acquire_for(std::chrono::seconds(30)))) return; - capy::abandon(slot); + slot.reset(); pool.join(); BOOST_TEST(child_at == pool_thread); BOOST_TEST(root_at == pool_thread); @@ -649,7 +638,7 @@ struct abandon_test if(!BOOST_TEST(done.try_acquire_for(std::chrono::seconds(30)))) return; - capy::abandon(slot); + slot.reset(); // The launch holds work on the caller until its unwind is done, // which follows the inner one. caller.join(); @@ -664,7 +653,7 @@ struct abandon_test { int posts = 0; counting_executor ex{&posts}; - chain_owner owner; + chain_state owner; owner.bind(std::noop_coroutine(), ex); owner.abandon(); owner.abandon(); @@ -672,22 +661,25 @@ struct abandon_test BOOST_TEST_EQ(posts, 1); } - // A continuation with no owner is destroyed directly. + // A standalone root chain_state with no executor is destroyed directly. void testAbandonWithoutOwnerDestroys() { int down = 0; auto probe = [](destroy_count_t) -> task { co_return; }; auto t = probe(destroy_count_t(down)); - continuation c{t.handle()}; + chain_state st; + st.bind_root(t.handle()); + st.arm_root(); t.release(); - capy::abandon(c); + auto c = coro_chain::from_address(&st); + c.reset(); BOOST_TEST_EQ(down, 1); } // An owner reads its segment's result once the segment completes. void testAbandonableSeesCompletion() { - std::queue q; + std::queue q; queuing_executor ex(q); parked slot; std::optional out; @@ -710,7 +702,7 @@ struct abandon_test // Abandoning the parked child resumes the owner with no result. void testAbandonableSeesAbandon() { - std::queue q; + std::queue q; queuing_executor ex(q); parked slot; std::optional out; @@ -723,12 +715,12 @@ struct abandon_test if(!BOOST_TEST(slot)) return; - capy::abandon(slot); + slot.reset(); if(!BOOST_TEST_EQ(q.size(), 1u)) return; - auto c = q.front(); + auto c = std::move(q.front()); q.pop(); - c.h.resume(); + c.resume(); BOOST_TEST_EQ(freed, 1); BOOST_TEST(!out); diff --git a/test/unit/ex/any_executor.cpp b/test/unit/ex/any_executor.cpp index 8d0a1ea2e..77319e7b1 100644 --- a/test/unit/ex/any_executor.cpp +++ b/test/unit/ex/any_executor.cpp @@ -49,11 +49,15 @@ struct counter_coro struct promise_type { std::atomic* counter; + chain_state chain_; counter_coro get_return_object() noexcept { - return counter_coro{std::coroutine_handle::from_promise(*this)}; + auto h = std::coroutine_handle::from_promise(*this); + chain_.bind_root(h); + chain_.arm_root(); + return counter_coro{h}; } std::suspend_always @@ -115,6 +119,13 @@ struct counter_coro h_ = nullptr; } + coro_chain + take_chain() noexcept + { + auto h = std::exchange(h_, nullptr); + return coro_chain::from_address(&h.promise().chain_); + } + private: explicit counter_coro(std::coroutine_handle h) : h_(h) @@ -153,8 +164,8 @@ struct counting_executor execution_context& context() const noexcept { return *ctx_; } void on_work_started() const noexcept { ++ctx_->work; } void on_work_finished() const noexcept { --ctx_->work; } - std::coroutine_handle<> dispatch(continuation& c) const { return c.h; } - void post(continuation&) const { } + std::coroutine_handle<> dispatch(coro_chain&& c) const { return c.release_handle(); } + void post(coro_chain&&) const { } }; static_assert(Executor); @@ -367,9 +378,7 @@ struct any_executor_test std::atomic counter{0}; auto coro = make_counter_coro(counter); - continuation c{coro.handle()}; - ex.dispatch(c); - coro.release(); + ex.dispatch(coro.take_chain()); BOOST_TEST(wait_for([&]{ return counter.load() >= 1; })); BOOST_TEST_EQ(counter.load(), 1); @@ -384,9 +393,7 @@ struct any_executor_test std::atomic counter{0}; auto coro = make_counter_coro(counter); - continuation c{coro.handle()}; - ex.post(c); - coro.release(); + ex.post(coro.take_chain()); BOOST_TEST(wait_for([&]{ return counter.load() >= 1; })); BOOST_TEST_EQ(counter.load(), 1); @@ -398,8 +405,6 @@ struct any_executor_test std::atomic counter{0}; constexpr int N = 10; - // continuations must outlive pool to avoid - // dangling pointers in the executor queue. counter_coro coros[N] = { make_counter_coro(counter), make_counter_coro(counter), @@ -412,7 +417,6 @@ struct any_executor_test make_counter_coro(counter), make_counter_coro(counter), }; - continuation conts[N] = {}; thread_pool pool(2); auto executor = pool.get_executor(); @@ -420,9 +424,7 @@ struct any_executor_test for(int i = 0; i < N; ++i) { - conts[i] = continuation{coros[i].handle()}; - ex.post(conts[i]); - coros[i].release(); + ex.post(coros[i].take_chain()); } BOOST_TEST(wait_for([&]{ return counter.load() >= N; })); @@ -434,14 +436,9 @@ struct any_executor_test { std::atomic counter{0}; - // continuations must outlive pool to avoid - // dangling pointers in the executor queue. auto coro1 = make_counter_coro(counter); auto coro2 = make_counter_coro(counter); auto coro3 = make_counter_coro(counter); - continuation c1{coro1.handle()}; - continuation c2{coro2.handle()}; - continuation c3{coro3.handle()}; thread_pool pool(1); auto executor = pool.get_executor(); @@ -456,12 +453,9 @@ struct any_executor_test BOOST_TEST(ex2 == ex3); // Post through different copies - ex1.post(c1); - coro1.release(); - ex2.post(c2); - coro2.release(); - ex3.post(c3); - coro3.release(); + ex1.post(coro1.take_chain()); + ex2.post(coro2.take_chain()); + ex3.post(coro3.take_chain()); BOOST_TEST(wait_for([&]{ return counter.load() >= 3; })); BOOST_TEST_EQ(counter.load(), 3); diff --git a/test/unit/ex/async_event.cpp b/test/unit/ex/async_event.cpp index 10a733b05..8fbba3add 100644 --- a/test/unit/ex/async_event.cpp +++ b/test/unit/ex/async_event.cpp @@ -12,7 +12,6 @@ #include #include -#include #include #include #include @@ -78,7 +77,7 @@ struct async_event_test testSingleWaiter() { async_event event; - std::queue q; + std::queue q; queuing_executor ex(q); bool resumed = false; @@ -90,8 +89,10 @@ struct async_event_test auto h = t.handle(); t.release(); + chain_state st; await_context env; env.executor = executor_ref(ex); + env.chain = &st; h.promise().set_environment(&env); h.resume(); @@ -101,7 +102,7 @@ struct async_event_test while(!q.empty()) { - q.front().h.resume(); + q.front().resume(); q.pop(); } @@ -114,7 +115,7 @@ struct async_event_test testMultipleWaiters() { async_event event; - std::queue q; + std::queue q; queuing_executor ex(q); int count = 0; @@ -137,11 +138,13 @@ struct async_event_test t2.release(); t3.release(); - await_context env; - env.executor = executor_ref(ex); - h1.promise().set_environment(&env); - h2.promise().set_environment(&env); - h3.promise().set_environment(&env); + chain_state st1, st2, st3; + await_context env1{executor_ref(ex), {}, nullptr, &st1}; + await_context env2{executor_ref(ex), {}, nullptr, &st2}; + await_context env3{executor_ref(ex), {}, nullptr, &st3}; + h1.promise().set_environment(&env1); + h2.promise().set_environment(&env2); + h3.promise().set_environment(&env3); h1.resume(); h2.resume(); @@ -152,7 +155,7 @@ struct async_event_test while(!q.empty()) { - q.front().h.resume(); + q.front().resume(); q.pop(); } @@ -194,7 +197,7 @@ struct async_event_test testSetClearSetSequence() { async_event event; - std::queue q; + std::queue q; queuing_executor ex(q); int count = 0; @@ -208,8 +211,10 @@ struct async_event_test auto h1 = t1.handle(); t1.release(); + chain_state st; await_context env; env.executor = executor_ref(ex); + env.chain = &st; h1.promise().set_environment(&env); h1.resume(); BOOST_TEST_EQ(count, 0); @@ -217,7 +222,7 @@ struct async_event_test event.set(); while(!q.empty()) { - q.front().h.resume(); + q.front().resume(); q.pop(); } BOOST_TEST_EQ(count, 1); @@ -241,7 +246,7 @@ struct async_event_test event.set(); while(!q.empty()) { - q.front().h.resume(); + q.front().resume(); q.pop(); } BOOST_TEST_EQ(count, 2); @@ -252,7 +257,7 @@ struct async_event_test testResumeOrder() { async_event event; - std::queue q; + std::queue q; queuing_executor ex(q); std::vector order; @@ -275,11 +280,13 @@ struct async_event_test t2.release(); t3.release(); - await_context env; - env.executor = executor_ref(ex); - h1.promise().set_environment(&env); - h2.promise().set_environment(&env); - h3.promise().set_environment(&env); + chain_state st1, st2, st3; + await_context env1{executor_ref(ex), {}, nullptr, &st1}; + await_context env2{executor_ref(ex), {}, nullptr, &st2}; + await_context env3{executor_ref(ex), {}, nullptr, &st3}; + h1.promise().set_environment(&env1); + h2.promise().set_environment(&env2); + h3.promise().set_environment(&env3); h1.resume(); h2.resume(); @@ -288,7 +295,7 @@ struct async_event_test event.set(); while(!q.empty()) { - q.front().h.resume(); + q.front().resume(); q.pop(); } @@ -315,7 +322,7 @@ struct async_event_test { // Stop token cancels a waiting coroutine async_event event; - std::queue q; + std::queue q; queuing_executor ex(q); std::stop_source ss; @@ -331,9 +338,11 @@ struct async_event_test auto h = t.handle(); t.release(); + chain_state st; await_context env; env.executor = executor_ref(ex); env.stop_token = ss.get_token(); + env.chain = &st; h.promise().set_environment(&env); h.resume(); @@ -343,7 +352,7 @@ struct async_event_test while(!q.empty()) { - q.front().h.resume(); + q.front().resume(); q.pop(); } @@ -359,7 +368,7 @@ struct async_event_test { // Cancel one waiter, set() wakes the rest async_event event; - std::queue q; + std::queue q; queuing_executor ex(q); std::stop_source ss; @@ -382,15 +391,18 @@ struct async_event_test auto h1 = w1.handle(); w1.release(); + chain_state st1, st2; await_context env1; env1.executor = executor_ref(ex); env1.stop_token = ss.get_token(); + env1.chain = &st1; h1.promise().set_environment(&env1); auto h2 = w2.handle(); w2.release(); await_context env2; env2.executor = executor_ref(ex); + env2.chain = &st2; h2.promise().set_environment(&env2); h1.resume(); @@ -402,7 +414,7 @@ struct async_event_test ss.request_stop(); while(!q.empty()) { - q.front().h.resume(); + q.front().resume(); q.pop(); } BOOST_TEST(w1_done); @@ -413,7 +425,7 @@ struct async_event_test event.set(); while(!q.empty()) { - q.front().h.resume(); + q.front().resume(); q.pop(); } BOOST_TEST(w2_done); @@ -428,7 +440,7 @@ struct async_event_test { // Pre-signaled token on contended event async_event event; - std::queue q; + std::queue q; queuing_executor ex(q); std::stop_source ss; ss.request_stop(); @@ -495,7 +507,7 @@ struct async_event_test // Destroying a coroutine while suspended properly // unlinks the awaiter async_event event; - std::queue q; + std::queue q; queuing_executor ex(q); auto t = [](async_event& ev) -> task { @@ -505,8 +517,10 @@ struct async_event_test auto h = t.handle(); t.release(); + chain_state st; await_context env; env.executor = executor_ref(ex); + env.chain = &st; h.promise().set_environment(&env); h.resume(); @@ -524,7 +538,7 @@ struct async_event_test // set() claims the waiter first, stop callback // loses the race -- no double resume async_event event; - std::queue q; + std::queue q; queuing_executor ex(q); std::stop_source ss; @@ -540,9 +554,11 @@ struct async_event_test auto h = t.handle(); t.release(); + chain_state st; await_context env; env.executor = executor_ref(ex); env.stop_token = ss.get_token(); + env.chain = &st; h.promise().set_environment(&env); h.resume(); BOOST_TEST(!done); @@ -555,7 +571,7 @@ struct async_event_test while(!q.empty()) { - q.front().h.resume(); + q.front().resume(); q.pop(); } @@ -583,8 +599,10 @@ struct async_event_test auto h = t.handle(); t.release(); + chain_state st; await_context env; env.executor = executor_ref(ex); + env.chain = &st; h.promise().set_environment(&env); h.resume(); @@ -626,11 +644,13 @@ struct async_event_test t2.release(); t3.release(); - await_context env; - env.executor = executor_ref(ex); - h1.promise().set_environment(&env); - h2.promise().set_environment(&env); - h3.promise().set_environment(&env); + chain_state st1, st2, st3; + await_context env1{executor_ref(ex), {}, nullptr, &st1}; + await_context env2{executor_ref(ex), {}, nullptr, &st2}; + await_context env3{executor_ref(ex), {}, nullptr, &st3}; + h1.promise().set_environment(&env1); + h2.promise().set_environment(&env2); + h3.promise().set_environment(&env3); h1.resume(); h2.resume(); @@ -668,9 +688,11 @@ struct async_event_test auto h = t.handle(); t.release(); + chain_state st; await_context env; env.executor = executor_ref(ex); env.stop_token = ss.get_token(); + env.chain = &st; h.promise().set_environment(&env); h.resume(); @@ -752,7 +774,7 @@ struct async_event_test auto [r] = co_await e.wait(); out = r; }; - std::queue q; + std::queue q; run_async(queuing_executor(q))(waiter(*ev, ec, destroy_count_t(down))); pump(q); ev.reset(); @@ -772,7 +794,7 @@ struct async_event_test int inner_down = 0, outer_down = 0, server_down = 0; int canceled = 0; parked slot; - std::queue q; + std::queue q; queuing_executor ex(q); auto inner = [&](async_event& e, destroy_count_t) -> task { @@ -799,13 +821,13 @@ struct async_event_test pump(q); BOOST_TEST(slot); - capy::abandon(slot); + slot.reset(); // Run only the posted unwind; the canceled waiters it posts // stay queued. BOOST_TEST_EQ(q.size(), 1u); - auto unwind = q.front(); + auto unwind = std::move(q.front()); q.pop(); - unwind.h.resume(); + unwind.resume(); BOOST_TEST_EQ(server_down, 1); BOOST_TEST_EQ(inner_down, 0); BOOST_TEST_EQ(q.size(), static_cast(count)); @@ -813,13 +835,13 @@ struct async_event_test // Half resume, half are torn down with their context. for(int i = 0; i < count / 2; ++i) { - auto c = q.front(); + auto c = std::move(q.front()); q.pop(); - c.h.resume(); + c.resume(); } while(!q.empty()) { - capy::abandon(q.front()); + q.front().reset(); q.pop(); } BOOST_TEST_EQ(canceled, count / 2); @@ -832,7 +854,7 @@ struct async_event_test // destroyed frame owned. void testSetWhenPostDestroysOwner() { - std::queue q; + std::queue q; auto ctx = std::make_unique(); queuing_executor qe(q); qe.ctx_ = ctx.get(); @@ -857,7 +879,7 @@ struct async_event_test // The same, with set() called from a destructor inside a teardown. void testSetFromTeardownWhenPostDestroysOwner() { - std::queue q; + std::queue q; auto ctx = std::make_unique(); queuing_executor qe(q); qe.ctx_ = ctx.get(); @@ -880,7 +902,7 @@ struct async_event_test ~set_on_exit() { (*e)->set(); } }; parked slot; - std::queue q2; + std::queue q2; auto notifier = [](async_event** e, parked* sl) -> task { @@ -892,7 +914,7 @@ struct async_event_test pump(q2); BOOST_TEST(slot); ctx->shutdown(); - capy::abandon(slot); + slot.reset(); pump(q2); BOOST_TEST_EQ(down, 1); } @@ -902,7 +924,7 @@ struct async_event_test void testStopClaimedWaiterOutlivesEvent() { auto p = std::make_unique(); - std::queue q; + std::queue q; std::stop_source ss; int down = 0; auto waiter = [](async_event& x, destroy_count_t) -> task @@ -915,7 +937,7 @@ struct async_event_test ss.request_stop(); BOOST_TEST_EQ(q.size(), 1u); p.reset(); - capy::abandon(q.front()); + q.front().reset(); q.pop(); pump(q); BOOST_TEST_EQ(down, 1); diff --git a/test/unit/ex/async_mutex.cpp b/test/unit/ex/async_mutex.cpp index 258143d66..3f7014010 100644 --- a/test/unit/ex/async_mutex.cpp +++ b/test/unit/ex/async_mutex.cpp @@ -12,7 +12,6 @@ #include #include -#include #include #include #include @@ -73,7 +72,7 @@ struct async_mutex_test testContendedLock() { async_mutex cm; - std::queue q; + std::queue q; queuing_executor ex(q); bool first_done = false; @@ -94,13 +93,14 @@ struct async_mutex_test auto h1 = first.handle(); first.release(); - await_context env; - env.executor = executor_ref(ex); - h1.promise().set_environment(&env); + chain_state st1, st2; + await_context env1{executor_ref(ex), {}, nullptr, &st1}; + await_context env2{executor_ref(ex), {}, nullptr, &st2}; + h1.promise().set_environment(&env1); auto h2 = second.handle(); second.release(); - h2.promise().set_environment(&env); + h2.promise().set_environment(&env2); h1.resume(); BOOST_TEST(first_done); @@ -113,7 +113,7 @@ struct async_mutex_test BOOST_TEST(!second_done); BOOST_TEST(!q.empty()); - q.front().h.resume(); + q.front().resume(); q.pop(); BOOST_TEST(second_done); BOOST_TEST(!cm.is_locked()); @@ -126,7 +126,7 @@ struct async_mutex_test testCancellation() { async_mutex cm; - std::queue q; + std::queue q; queuing_executor ex(q); std::stop_source ss; @@ -149,8 +149,10 @@ struct async_mutex_test auto h1 = holder.handle(); holder.release(); + chain_state st1, st2; await_context env1; env1.executor = executor_ref(ex); + env1.chain = &st1; h1.promise().set_environment(&env1); auto h2 = waiter.handle(); @@ -158,6 +160,7 @@ struct async_mutex_test await_context env2; env2.executor = executor_ref(ex); env2.stop_token = ss.get_token(); + env2.chain = &st2; h2.promise().set_environment(&env2); h1.resume(); @@ -169,7 +172,7 @@ struct async_mutex_test ss.request_stop(); BOOST_TEST(!q.empty()); - q.front().h.resume(); + q.front().resume(); q.pop(); BOOST_TEST(waiter_done); @@ -187,7 +190,7 @@ struct async_mutex_test testScopedLockCancellation() { async_mutex cm; - std::queue q; + std::queue q; queuing_executor ex(q); std::stop_source ss; @@ -210,8 +213,10 @@ struct async_mutex_test auto h1 = holder.handle(); holder.release(); + chain_state st1, st2; await_context env1; env1.executor = executor_ref(ex); + env1.chain = &st1; h1.promise().set_environment(&env1); auto h2 = waiter.handle(); @@ -219,6 +224,7 @@ struct async_mutex_test await_context env2; env2.executor = executor_ref(ex); env2.stop_token = ss.get_token(); + env2.chain = &st2; h2.promise().set_environment(&env2); h1.resume(); @@ -230,7 +236,7 @@ struct async_mutex_test ss.request_stop(); BOOST_TEST(!q.empty()); - q.front().h.resume(); + q.front().resume(); q.pop(); BOOST_TEST(waiter_done); @@ -248,7 +254,7 @@ struct async_mutex_test testDestroyWhileSuspended() { async_mutex cm; - std::queue q; + std::queue q; queuing_executor ex(q); bool holder_done = false; @@ -266,8 +272,10 @@ struct async_mutex_test auto h1 = holder.handle(); holder.release(); + chain_state st; await_context env; env.executor = executor_ref(ex); + env.chain = &st; h1.promise().set_environment(&env); auto h2 = waiter.handle(); @@ -291,7 +299,7 @@ struct async_mutex_test testUnlockSkipsCanceled() { async_mutex cm; - std::queue q; + std::queue q; queuing_executor ex(q); std::stop_source ss1; std::stop_source ss2; @@ -330,28 +338,23 @@ struct async_mutex_test auto hh = holder.handle(); holder.release(); - await_context env_h; - env_h.executor = executor_ref(ex); + chain_state st_h, st1, st2, st3; + await_context env_h{executor_ref(ex), {}, nullptr, &st_h}; hh.promise().set_environment(&env_h); auto h1 = w1.handle(); w1.release(); - await_context env1; - env1.executor = executor_ref(ex); - env1.stop_token = ss1.get_token(); + await_context env1{executor_ref(ex), ss1.get_token(), nullptr, &st1}; h1.promise().set_environment(&env1); auto h2 = w2.handle(); w2.release(); - await_context env2; - env2.executor = executor_ref(ex); - env2.stop_token = ss2.get_token(); + await_context env2{executor_ref(ex), ss2.get_token(), nullptr, &st2}; h2.promise().set_environment(&env2); auto h3 = w3.handle(); w3.release(); - await_context env3; - env3.executor = executor_ref(ex); + await_context env3{executor_ref(ex), {}, nullptr, &st3}; h3.promise().set_environment(&env3); hh.resume(); @@ -366,7 +369,7 @@ struct async_mutex_test while(!q.empty()) { - q.front().h.resume(); + q.front().resume(); q.pop(); } @@ -380,7 +383,7 @@ struct async_mutex_test while(!q.empty()) { - q.front().h.resume(); + q.front().resume(); q.pop(); } @@ -404,7 +407,7 @@ struct async_mutex_test // remove() must be idempotent so this second unlink is a no-op. // The queuing executor makes the interleaving deterministic. async_mutex cm; - std::queue q; + std::queue q; queuing_executor ex(q); std::stop_source ss1; @@ -434,21 +437,18 @@ struct async_mutex_test auto hh = holder.handle(); holder.release(); - await_context env_h; - env_h.executor = executor_ref(ex); + chain_state st_h, st1, st2; + await_context env_h{executor_ref(ex), {}, nullptr, &st_h}; hh.promise().set_environment(&env_h); auto h1 = w1.handle(); w1.release(); - await_context env1; - env1.executor = executor_ref(ex); - env1.stop_token = ss1.get_token(); + await_context env1{executor_ref(ex), ss1.get_token(), nullptr, &st1}; h1.promise().set_environment(&env1); auto h2 = w2.handle(); w2.release(); - await_context env2; - env2.executor = executor_ref(ex); + await_context env2{executor_ref(ex), {}, nullptr, &st2}; h2.promise().set_environment(&env2); hh.resume(); @@ -467,7 +467,7 @@ struct async_mutex_test while(!q.empty()) { - q.front().h.resume(); + q.front().resume(); q.pop(); } @@ -488,7 +488,7 @@ struct async_mutex_test testPreSignaledToken() { async_mutex cm; - std::queue q; + std::queue q; queuing_executor ex(q); std::stop_source ss; ss.request_stop(); @@ -602,7 +602,7 @@ struct async_mutex_test testPreSignaledScopedLock() { async_mutex cm; - std::queue q; + std::queue q; queuing_executor ex(q); std::stop_source ss; ss.request_stop(); @@ -656,7 +656,7 @@ struct async_mutex_test testFIFOOrder() { async_mutex cm; - std::queue q; + std::queue q; queuing_executor ex(q); int order = 0; @@ -690,21 +690,24 @@ struct async_mutex_test auto hh = holder.handle(); holder.release(); - await_context env; - env.executor = executor_ref(ex); - hh.promise().set_environment(&env); + chain_state st_h, st1, st2, st3; + await_context env_h{executor_ref(ex), {}, nullptr, &st_h}; + await_context env1{executor_ref(ex), {}, nullptr, &st1}; + await_context env2{executor_ref(ex), {}, nullptr, &st2}; + await_context env3{executor_ref(ex), {}, nullptr, &st3}; + hh.promise().set_environment(&env_h); auto h1 = w1.handle(); w1.release(); - h1.promise().set_environment(&env); + h1.promise().set_environment(&env1); auto h2 = w2.handle(); w2.release(); - h2.promise().set_environment(&env); + h2.promise().set_environment(&env2); auto h3 = w3.handle(); w3.release(); - h3.promise().set_environment(&env); + h3.promise().set_environment(&env3); hh.resume(); h1.resume(); @@ -714,7 +717,7 @@ struct async_mutex_test cm.unlock(); while(!q.empty()) { - q.front().h.resume(); + q.front().resume(); q.pop(); } @@ -733,7 +736,7 @@ struct async_mutex_test testCancelMiddleWaiter() { async_mutex cm; - std::queue q; + std::queue q; queuing_executor ex(q); std::stop_source ss; @@ -770,27 +773,23 @@ struct async_mutex_test auto hh = holder.handle(); holder.release(); - await_context env_h; - env_h.executor = executor_ref(ex); + chain_state st_h, st1, st2, st3; + await_context env_h{executor_ref(ex), {}, nullptr, &st_h}; hh.promise().set_environment(&env_h); auto h1 = w1.handle(); w1.release(); - await_context env1; - env1.executor = executor_ref(ex); + await_context env1{executor_ref(ex), {}, nullptr, &st1}; h1.promise().set_environment(&env1); auto h2 = w2.handle(); w2.release(); - await_context env2; - env2.executor = executor_ref(ex); - env2.stop_token = ss.get_token(); + await_context env2{executor_ref(ex), ss.get_token(), nullptr, &st2}; h2.promise().set_environment(&env2); auto h3 = w3.handle(); w3.release(); - await_context env3; - env3.executor = executor_ref(ex); + await_context env3{executor_ref(ex), {}, nullptr, &st3}; h3.promise().set_environment(&env3); hh.resume(); @@ -801,7 +800,7 @@ struct async_mutex_test ss.request_stop(); while(!q.empty()) { - q.front().h.resume(); + q.front().resume(); q.pop(); } BOOST_TEST(w2_done); @@ -810,7 +809,7 @@ struct async_mutex_test cm.unlock(); while(!q.empty()) { - q.front().h.resume(); + q.front().resume(); q.pop(); } @@ -828,7 +827,7 @@ struct async_mutex_test testDestroyMultipleSuspended() { async_mutex cm; - std::queue q; + std::queue q; queuing_executor ex(q); auto holder = [](async_mutex& cm) -> task { @@ -848,17 +847,19 @@ struct async_mutex_test auto hh = holder.handle(); holder.release(); - await_context env; - env.executor = executor_ref(ex); - hh.promise().set_environment(&env); + chain_state st_h, st1, st2; + await_context env_h{executor_ref(ex), {}, nullptr, &st_h}; + await_context env1{executor_ref(ex), {}, nullptr, &st1}; + await_context env2{executor_ref(ex), {}, nullptr, &st2}; + hh.promise().set_environment(&env_h); auto h1 = w1.handle(); w1.release(); - h1.promise().set_environment(&env); + h1.promise().set_environment(&env1); auto h2 = w2.handle(); w2.release(); - h2.promise().set_environment(&env); + h2.promise().set_environment(&env2); hh.resume(); h1.resume(); @@ -931,13 +932,14 @@ struct async_mutex_test auto h1 = first.handle(); first.release(); - await_context env; - env.executor = executor_ref(ex); - h1.promise().set_environment(&env); + chain_state st1, st2; + await_context env1{executor_ref(ex), {}, nullptr, &st1}; + await_context env2{executor_ref(ex), {}, nullptr, &st2}; + h1.promise().set_environment(&env1); auto h2 = second.handle(); second.release(); - h2.promise().set_environment(&env); + h2.promise().set_environment(&env2); h1.resume(); BOOST_TEST(first_done); @@ -984,15 +986,13 @@ struct async_mutex_test auto h1 = holder.handle(); holder.release(); - await_context env1; - env1.executor = executor_ref(ex); + chain_state st1, st2; + await_context env1{executor_ref(ex), {}, nullptr, &st1}; h1.promise().set_environment(&env1); auto h2 = waiter.handle(); waiter.release(); - await_context env2; - env2.executor = executor_ref(ex); - env2.stop_token = ss.get_token(); + await_context env2{executor_ref(ex), ss.get_token(), nullptr, &st2}; h2.promise().set_environment(&env2); h1.resume(); @@ -1028,7 +1028,7 @@ struct async_mutex_test auto [e] = co_await mx.lock(); out = e; }; - std::queue q; + std::queue q; run_async(queuing_executor(q))(waiter(*m, ec, destroy_count_t(down))); pump(q); m.reset(); @@ -1046,7 +1046,7 @@ struct async_mutex_test { int down = 0; parked slot; - std::queue q; + std::queue q; queuing_executor ex(q); int resumed = 0; auto waiter = [](async_mutex& mx, int& resumed, destroy_count_t) @@ -1070,10 +1070,10 @@ struct async_mutex_test run_async(ex, std::allocator{})(owner()); pump(q); BOOST_TEST(slot); - capy::abandon(slot); + slot.reset(); while(!q.empty()) { - capy::abandon(q.front()); + q.front().reset(); q.pop(); } BOOST_TEST_EQ(down, 2); @@ -1084,7 +1084,7 @@ struct async_mutex_test // destroys it destroys the mutex while unlock() is still running. void testUnlockWhenPostDestroysOwner() { - std::queue q; + std::queue q; auto ctx = std::make_unique(); queuing_executor qe(q); qe.ctx_ = ctx.get(); @@ -1112,7 +1112,7 @@ struct async_mutex_test void testHandoffChainDoesNotRecurse() { constexpr int count = 100000; - std::queue q; + std::queue q; auto ctx = std::make_unique(); queuing_executor qe(q); qe.ctx_ = ctx.get(); @@ -1145,12 +1145,12 @@ struct async_mutex_test { std::ignore = co_await mx.lock(); }; - std::queue q; + std::queue q; run_async(queuing_executor(q))(waiter(*m, destroy_count_t(down))); pump(q); m.reset(); BOOST_TEST_EQ(q.size(), 1u); - capy::abandon(q.front()); + q.front().reset(); q.pop(); pump(q); BOOST_TEST_EQ(down, 1); @@ -1162,7 +1162,7 @@ struct async_mutex_test { async_mutex m; BOOST_TEST(m.lock().await_ready()); - std::queue q; + std::queue q; auto waiter = [](async_mutex& mx) -> task { std::ignore = co_await mx.lock(); @@ -1172,7 +1172,7 @@ struct async_mutex_test pump(q); // waiter queued on the mutex m.unlock(); // hands the lock over, posts the waiter BOOST_TEST_EQ(q.size(), 1u); - capy::abandon(q.front()); // torn down before it resumes + q.front().reset(); // torn down before it resumes q.pop(); pump(q); BOOST_TEST(!m.is_locked()); @@ -1183,7 +1183,7 @@ struct async_mutex_test void testStopClaimedWaiterOutlivesMutex() { auto p = std::make_unique(); - std::queue q; + std::queue q; std::stop_source ss; // Held by the test, not a coroutine: nothing unlocks it later, // and unlocking first would pop the claimed waiter before the @@ -1200,7 +1200,7 @@ struct async_mutex_test ss.request_stop(); BOOST_TEST_EQ(q.size(), 1u); p.reset(); - capy::abandon(q.front()); + q.front().reset(); q.pop(); pump(q); BOOST_TEST_EQ(down, 1); diff --git a/test/unit/ex/async_waker.cpp b/test/unit/ex/async_waker.cpp index 5dea31a4c..d82380b2d 100644 --- a/test/unit/ex/async_waker.cpp +++ b/test/unit/ex/async_waker.cpp @@ -11,7 +11,6 @@ #include #include -#include #include #include #include @@ -40,7 +39,7 @@ class worker { std::mutex m_; std::condition_variable cv_; - std::deque q_; + std::deque q_; bool running_ = false; bool stop_ = false; std::thread t_; @@ -53,11 +52,11 @@ class worker cv_.wait(lk, [&]{ return stop_ || !q_.empty(); }); if(q_.empty()) return; - auto c = q_.front(); + auto c = std::move(q_.front()); q_.pop_front(); running_ = true; lk.unlock(); - c.h.resume(); + c.resume(); lk.lock(); running_ = false; } @@ -85,11 +84,11 @@ class worker return q_.empty() && !running_; } - void push(continuation const& c) + void push(coro_chain&& c) { { std::lock_guard lk(m_); - q_.push_back(c); + q_.push_back(std::move(c)); } cv_.notify_one(); } @@ -109,14 +108,14 @@ struct worker_executor } void on_work_started() const noexcept {} void on_work_finished() const noexcept {} - std::coroutine_handle<> dispatch(continuation& c) const + std::coroutine_handle<> dispatch(coro_chain&& c) const { - w_->push(c); + w_->push(std::move(c)); return std::noop_coroutine(); } - void post(continuation& c) const + void post(coro_chain&& c) const { - w_->push(c); + w_->push(std::move(c)); } }; @@ -356,7 +355,7 @@ struct async_waker_test void testDestroyWaitingFrame() { async_waker waker; - std::queue q; + std::queue q; queuing_executor ex(q); int down = 0; auto t = [](async_waker& wk, destroy_count_t) -> task @@ -365,8 +364,10 @@ struct async_waker_test }(waker, destroy_count_t(down)); auto h = t.handle(); t.release(); + chain_state st; await_context env; env.executor = executor_ref(ex); + env.chain = &st; h.promise().set_environment(&env); h.resume(); BOOST_TEST_EQ(down, 0); @@ -399,7 +400,7 @@ struct async_waker_test auto [e] = co_await wk.wait(); out = e; }; - std::queue q; + std::queue q; run_async(queuing_executor(q))(waiter(*w, ec, destroy_count_t(down))); pump(q); w.reset(); @@ -450,7 +451,7 @@ struct async_waker_test { int down = 0; auto p = std::make_unique(); - std::queue q; + std::queue q; auto waiter = [](async_waker& x, destroy_count_t) -> task { std::ignore = co_await x.wait(); @@ -460,7 +461,7 @@ struct async_waker_test pump(q); p->wake(); BOOST_TEST_EQ(q.size(), 1u); - capy::abandon(q.front()); + q.front().reset(); q.pop(); pump(q); p.reset(); @@ -515,7 +516,7 @@ struct async_waker_test auto [e] = co_await wk.wait(); out = e; }; - std::queue q; + std::queue q; run_async(queuing_executor(q), ss.get_token(), std::allocator{})(waiter(*w, ec)); pump(q); @@ -540,7 +541,7 @@ struct async_waker_test auto [e] = co_await wk.wait(); out = e; }; - std::queue q; + std::queue q; run_async(queuing_executor(q), ss.get_token())(waiter(*w, ec)); pump(q); w.reset(); @@ -555,7 +556,7 @@ struct async_waker_test void testStopClaimedWaiterOutlivesWaker() { auto p = std::make_unique(); - std::queue q; + std::queue q; std::stop_source ss; int down = 0; auto waiter = [](async_waker& x, destroy_count_t) -> task @@ -568,7 +569,7 @@ struct async_waker_test ss.request_stop(); BOOST_TEST_EQ(q.size(), 1u); p.reset(); - capy::abandon(q.front()); + q.front().reset(); q.pop(); pump(q); BOOST_TEST_EQ(down, 1); @@ -578,7 +579,7 @@ struct async_waker_test void testWakeClaimedWaiterOutlivesWaker() { auto p = std::make_unique(); - std::queue q; + std::queue q; int down = 0; auto waiter = [](async_waker& x, destroy_count_t) -> task { @@ -590,7 +591,7 @@ struct async_waker_test p->wake(); BOOST_TEST_EQ(q.size(), 1u); p.reset(); - capy::abandon(q.front()); + q.front().reset(); q.pop(); pump(q); BOOST_TEST_EQ(down, 1); diff --git a/test/unit/ex/executor_ref.cpp b/test/unit/ex/executor_ref.cpp index abf7724d9..edf75ddc4 100644 --- a/test/unit/ex/executor_ref.cpp +++ b/test/unit/ex/executor_ref.cpp @@ -45,11 +45,15 @@ struct counter_coro struct promise_type { std::atomic* counter; + chain_state chain_; counter_coro get_return_object() noexcept { - return counter_coro{std::coroutine_handle::from_promise(*this)}; + auto h = std::coroutine_handle::from_promise(*this); + chain_.bind_root(h); + chain_.arm_root(); + return counter_coro{h}; } std::suspend_always @@ -111,6 +115,13 @@ struct counter_coro h_ = nullptr; } + coro_chain + take_chain() noexcept + { + auto h = std::exchange(h_, nullptr); + return coro_chain::from_address(&h.promise().chain_); + } + private: explicit counter_coro(std::coroutine_handle h) : h_(h) @@ -149,8 +160,8 @@ struct counting_executor execution_context& context() const noexcept { return *ctx_; } void on_work_started() const noexcept { ++ctx_->work; } void on_work_finished() const noexcept { --ctx_->work; } - std::coroutine_handle<> dispatch(continuation& c) const { return c.h; } - void post(continuation&) const { } + std::coroutine_handle<> dispatch(coro_chain&& c) const { return c.release_handle(); } + void post(coro_chain&&) const { } }; static_assert(Executor); @@ -242,9 +253,7 @@ struct executor_ref_test std::atomic counter{0}; auto coro = make_counter_coro(counter); - continuation c{coro.handle()}; - ex.dispatch(c); - coro.release(); + ex.dispatch(coro.take_chain()); BOOST_TEST(wait_for([&]{ return counter.load() >= 1; })); BOOST_TEST_EQ(counter.load(), 1); @@ -259,9 +268,7 @@ struct executor_ref_test std::atomic counter{0}; auto coro = make_counter_coro(counter); - continuation c{coro.handle()}; - ex.post(c); - coro.release(); + ex.post(coro.take_chain()); BOOST_TEST(wait_for([&]{ return counter.load() >= 1; })); BOOST_TEST_EQ(counter.load(), 1); @@ -273,8 +280,6 @@ struct executor_ref_test std::atomic counter{0}; constexpr int N = 10; - // continuations must outlive pool to avoid - // dangling pointers in the executor queue. counter_coro coros[N] = { make_counter_coro(counter), make_counter_coro(counter), @@ -287,7 +292,6 @@ struct executor_ref_test make_counter_coro(counter), make_counter_coro(counter), }; - continuation conts[N] = {}; thread_pool pool(2); auto executor = pool.get_executor(); @@ -295,9 +299,7 @@ struct executor_ref_test for(int i = 0; i < N; ++i) { - conts[i] = continuation{coros[i].handle()}; - ex.post(conts[i]); - coros[i].release(); + ex.post(coros[i].take_chain()); } BOOST_TEST(wait_for([&]{ return counter.load() >= N; })); diff --git a/test/unit/ex/frame_cb.cpp b/test/unit/ex/frame_cb.cpp index 9f72f67da..6b216e042 100644 --- a/test/unit/ex/frame_cb.cpp +++ b/test/unit/ex/frame_cb.cpp @@ -8,9 +8,10 @@ // #include -#include +#include #include #include +#include #include #include #include @@ -26,16 +27,47 @@ namespace boost { namespace capy { -namespace detail { +namespace { -struct frame_cb +struct test_cb_node : frame_cb { - void (*resume)(frame_cb*); - void (*destroy)(frame_cb*); - void* data; + void* data = nullptr; }; -} // detail +struct callback_root_probe : root_work_base +{ + task t_; + int* out_ = nullptr; + int* abandoned_ = nullptr; + + callback_root_probe(task&& t, int& out, int& ab) + : t_(std::move(t)) + , out_(&out) + , abandoned_(&ab) + { + } + + void start(executor_ref ex) + { + auto h = this->bind_chain(ex); + auto next = t_.await_suspend(h, &this->env_); + if(next != std::noop_coroutine()) + next.resume(); + } + + void on_resume() + { + *out_ = t_.await_resume(); + } + + void on_abandon() noexcept + { + ++*abandoned_; + t_ = task{}; + } +}; + +} // namespace struct frame_cb_test { @@ -43,14 +75,14 @@ struct frame_cb_test testResumeCallsFunctionPointer() { bool called = false; - detail::frame_cb cb; - cb.resume = +[](detail::frame_cb* p) { - *static_cast(p->data) = true; + test_cb_node cb; + cb.resume = +[](frame_cb* p) { + *static_cast(static_cast(p)->data) = true; }; - cb.destroy = +[](detail::frame_cb*) {}; + cb.destroy = +[](frame_cb*) {}; cb.data = &called; - cb.resume(&cb); + cb.handle().resume(); BOOST_TEST(called); } @@ -58,14 +90,14 @@ struct frame_cb_test testDestroyIsNoOp() { bool destroy_called = false; - detail::frame_cb cb; - cb.resume = +[](detail::frame_cb*) {}; - cb.destroy = +[](detail::frame_cb* p) { - *static_cast(p->data) = true; + test_cb_node cb; + cb.resume = +[](frame_cb*) {}; + cb.destroy = +[](frame_cb* p) { + *static_cast(static_cast(p)->data) = true; }; cb.data = &destroy_called; - cb.destroy(&cb); + cb.handle().destroy(); BOOST_TEST(destroy_called); } @@ -73,17 +105,56 @@ struct frame_cb_test testDataPointerPassedThrough() { int value = 0; - detail::frame_cb cb; - cb.resume = +[](detail::frame_cb* p) { - *static_cast(p->data) = 42; + test_cb_node cb; + cb.resume = +[](frame_cb* p) { + *static_cast(static_cast(p)->data) = 42; }; - cb.destroy = +[](detail::frame_cb*) {}; + cb.destroy = +[](frame_cb*) {}; cb.data = &value; - cb.resume(&cb); + cb.handle().resume(); BOOST_TEST_EQ(value, 42); } + void + testRootWorkBaseResumeAndAbandon() + { + std::queue q; + queuing_executor ex(q); + + // 1. Normal completion through root_work_base + { + int out = 0, ab = 0; + auto body = []() -> task { co_return 77; }; + callback_root_probe probe(body(), out, ab); + probe.start(ex); + BOOST_TEST_EQ(out, 77); + BOOST_TEST_EQ(ab, 0); + } + + // 2. Abandonment through root_work_base unwinds inner task + { + int out = 0, ab = 0, child_down = 0; + parked slot; + auto body = [](parked* s, destroy_count_t) -> task + { + co_await park_awaitable{s}; + co_return 11; + }; + callback_root_probe probe( + body(&slot, destroy_count_t(child_down)), out, ab); + probe.start(ex); + BOOST_TEST(slot); + BOOST_TEST_EQ(child_down, 0); + + slot.reset(); + pump(q); + BOOST_TEST_EQ(out, 0); + BOOST_TEST_EQ(ab, 1); + BOOST_TEST_EQ(child_down, 1); + } + } + // ContextAwaitable that resumes synchronously and returns a value struct sync_awaitable { @@ -131,7 +202,6 @@ struct frame_cb_test struct async_awaitable { int value; - continuation cont_; bool await_ready() const noexcept { @@ -143,8 +213,7 @@ struct frame_cb_test std::coroutine_handle<> h, await_context const* env) noexcept { - cont_.h = h; - env->executor.post(cont_); + env->executor.post(env->park(h)); return std::noop_coroutine(); } @@ -159,7 +228,7 @@ struct frame_cb_test static task await_async(int v) { - auto [ec, result] = co_await async_awaitable{v, {}}; + auto [ec, result] = co_await async_awaitable{v}; co_return result; } @@ -190,6 +259,7 @@ struct frame_cb_test testResumeCallsFunctionPointer(); testDestroyIsNoOp(); testDataPointerPassedThrough(); + testRootWorkBaseResumeAndAbandon(); testWithContextAwaitable(); testWithAsyncAwaitable(); } diff --git a/test/unit/ex/priority_executor.hpp b/test/unit/ex/priority_executor.hpp index 1986c23fa..984c3cb7b 100644 --- a/test/unit/ex/priority_executor.hpp +++ b/test/unit/ex/priority_executor.hpp @@ -11,7 +11,7 @@ #define BOOST_CAPY_TEST_UNIT_EX_PRIORITY_EXECUTOR_HPP #include -#include +#include #include #include #include @@ -33,10 +33,8 @@ namespace test { struct priority_executor_state { std::mutex mutex; - continuation* high_head = nullptr; - continuation* high_tail = nullptr; - continuation* low_head = nullptr; - continuation* low_tail = nullptr; + chain_queue high_q; + chain_queue low_q; bool locked = false; std::atomic dispatch_thread{}; }; @@ -47,7 +45,7 @@ struct priority_invoker { struct promise_type { - continuation self; + ::boost::capy::chain_state self; priority_invoker get_return_object() noexcept { @@ -64,15 +62,10 @@ struct priority_invoker }; inline void -drain_list(continuation* head) noexcept +drain_list(chain_queue& q) noexcept { - while(head) - { - continuation* c = head; - head = static_cast(c->reserved); - c->reserved = nullptr; - ::boost::capy::safe_resume(c->h); - } + while(auto c = q.pop()) + c.resume(); } inline priority_invoker @@ -84,24 +77,20 @@ make_priority_invoker(priority_executor_state* s) std::this_thread::get_id(), std::memory_order_release); - continuation* high_head; - continuation* low_head; + chain_queue high_batch; + chain_queue low_batch; { std::lock_guard lk(s->mutex); - high_head = s->high_head; - low_head = s->low_head; - s->high_head = nullptr; - s->high_tail = nullptr; - s->low_head = nullptr; - s->low_tail = nullptr; + high_batch = std::move(s->high_q); + low_batch = std::move(s->low_q); } - drain_list(high_head); - drain_list(low_head); + drain_list(high_batch); + drain_list(low_batch); { std::lock_guard lk(s->mutex); - if(!s->high_head && !s->low_head) + if(s->high_q.empty() && s->low_q.empty()) { s->locked = false; s->dispatch_thread.store( @@ -127,30 +116,21 @@ class priority_executor enum class priority { high, low }; void - enqueue_under_lock(continuation& c, priority p) const noexcept + enqueue_under_lock(coro_chain&& c, priority p) const noexcept { - c.reserved = nullptr; if(p == priority::high) - { - if(state_->high_tail) state_->high_tail->reserved = &c; - else state_->high_head = &c; - state_->high_tail = &c; - } + state_->high_q.push(std::move(c)); else - { - if(state_->low_tail) state_->low_tail->reserved = &c; - else state_->low_head = &c; - state_->low_tail = &c; - } + state_->low_q.push(std::move(c)); } void - post_with_priority(continuation& c, priority p) const + post_with_priority(coro_chain&& c, priority p) const { bool first; { std::lock_guard lk(state_->mutex); - enqueue_under_lock(c, p); + enqueue_under_lock(std::move(c), p); first = !state_->locked; if(first) state_->locked = true; } @@ -163,9 +143,9 @@ class priority_executor { auto inv = detail::make_priority_invoker(state_); auto& self = inv.h_.promise().self; - self.h = inv.h_; - self.reserved = nullptr; - inner_ex_.post(self); + self.bind_root(inv.h_); + self.arm_root(); + inner_ex_.post(coro_chain::from_address(&self)); } public: @@ -207,30 +187,30 @@ class priority_executor } std::coroutine_handle<> - dispatch(continuation& c) const + dispatch(coro_chain&& c) const { if(running_in_this_thread()) - return c.h; - post_with_priority(c, priority::low); + return c.release_handle(); + post_with_priority(std::move(c), priority::low); return std::noop_coroutine(); } void - post(continuation& c) const + post(coro_chain&& c) const { - post_with_priority(c, priority::low); + post_with_priority(std::move(c), priority::low); } void - post_high(continuation& c) const + post_high(coro_chain&& c) const { - post_with_priority(c, priority::high); + post_with_priority(std::move(c), priority::high); } void - post_low(continuation& c) const + post_low(coro_chain&& c) const { - post_with_priority(c, priority::low); + post_with_priority(std::move(c), priority::low); } }; diff --git a/test/unit/ex/run.cpp b/test/unit/ex/run.cpp index d37a796ea..0f67a22c8 100644 --- a/test/unit/ex/run.cpp +++ b/test/unit/ex/run.cpp @@ -11,7 +11,6 @@ #include #include -#include #include #include #include @@ -72,7 +71,7 @@ struct park_plain parked* slot; bool await_ready() const noexcept { return false; } - void await_suspend(std::coroutine_handle<> h) noexcept { slot->h = h; } + void await_suspend(std::coroutine_handle<> h) noexcept { slot->raw_h_ = h; } void await_resume() const noexcept {} }; @@ -636,7 +635,7 @@ struct run_test // Executor that queues posts and counts outstanding work. struct counting_queue_executor { - std::queue* q_; + std::queue* q_; int* work_; bool operator==(counting_queue_executor const& o) const noexcept @@ -649,14 +648,14 @@ struct run_test } void on_work_started() const noexcept { ++*work_; } void on_work_finished() const noexcept { --*work_; } - std::coroutine_handle<> dispatch(continuation& c) const + std::coroutine_handle<> dispatch(coro_chain&& c) const { - q_->push(c); + q_->push(std::move(c)); return std::noop_coroutine(); } - void post(continuation& c) const + void post(coro_chain&& c) const { - q_->push(c); + q_->push(std::move(c)); } }; @@ -680,7 +679,7 @@ struct run_test }; run_async(caller)(owner(destroy_count_t(owner_down))); BOOST_TEST(slot); - capy::abandon(slot); + slot.reset(); BOOST_TEST_EQ(child_down, 1); BOOST_TEST_EQ(owner_down, 1); BOOST_TEST(mr.allocs.load() > 0); @@ -708,7 +707,7 @@ struct run_test BOOST_TEST(slot); auto* const before = get_current_frame_allocator(); set_current_frame_allocator(&mine); - capy::abandon(slot); + slot.reset(); BOOST_TEST(get_current_frame_allocator() == &mine); set_current_frame_allocator(before); } @@ -717,7 +716,7 @@ struct run_test void testInnerTeardownFreesBeforeResourceOwnerEx() { lease_resource mr; - std::queue q; + std::queue q; int child_down = 0, owner_down = 0, n = 0; parked slot; queuing_executor caller(q); @@ -736,7 +735,7 @@ struct run_test run_async(caller)(owner(destroy_count_t(owner_down))); pump(q); BOOST_TEST(slot); - capy::abandon(slot); + slot.reset(); pump(q); BOOST_TEST_EQ(child_down, 1); BOOST_TEST_EQ(owner_down, 1); @@ -765,7 +764,7 @@ struct run_test }; run_async(caller)(parent(destroy_count_t(parent_down))); BOOST_TEST(slot); - capy::abandon(slot); + slot.reset(); } BOOST_TEST_EQ(child_down, 1); BOOST_TEST_EQ(parent_down, 1); @@ -778,7 +777,7 @@ struct run_test void testInnerTeardownWithRunExAllocator() { alloc_counts st; - std::queue q; + std::queue q; int child_down = 0, parent_down = 0, n = 0; parked slot; { @@ -797,7 +796,7 @@ struct run_test run_async(caller)(parent(destroy_count_t(parent_down))); pump(q); BOOST_TEST(slot); - capy::abandon(slot); + slot.reset(); pump(q); } BOOST_TEST_EQ(child_down, 1); @@ -810,7 +809,7 @@ struct run_test // the caller's executor; running it destroys the parent there. void testInnerTeardownReapsParentOnCallerExecutor() { - std::queue q; + std::queue q; int work = 0, child_down = 0, parent_down = 0, n = 0; parked slot; counting_queue_executor caller{&q, &work}; @@ -828,7 +827,7 @@ struct run_test BOOST_TEST(slot); BOOST_TEST_EQ(work, 2); // run_async's guard and run(ex)'s hold - capy::abandon(slot); + slot.reset(); BOOST_TEST_EQ(child_down, 1); BOOST_TEST_EQ(parent_down, 0); // not inline: queued on caller BOOST_TEST_EQ(q.size(), 1u); @@ -845,7 +844,7 @@ struct run_test { struct closing_executor { - std::queue* q_; + std::queue* q_; bool* closed_; bool operator==(closing_executor const& o) const noexcept @@ -858,21 +857,21 @@ struct run_test } void on_work_started() const noexcept {} void on_work_finished() const noexcept {} - std::coroutine_handle<> dispatch(continuation& c) const + std::coroutine_handle<> dispatch(coro_chain&& c) const { - post(c); + post(std::move(c)); return std::noop_coroutine(); } - void post(continuation& c) const + void post(coro_chain&& c) const { if(*closed_) - capy::abandon(c); + c.reset(); else - q_->push(c); + q_->push(std::move(c)); } }; alloc_counts st; - std::queue q; + std::queue q; bool closed = false; int child_down = 0, parent_down = 0, n = 0; parked slot; @@ -891,7 +890,7 @@ struct run_test pump(q); BOOST_TEST(slot); closed = true; - capy::abandon(slot); + slot.reset(); BOOST_TEST_EQ(child_down, 1); BOOST_TEST_EQ(parent_down, 1); BOOST_TEST(st.allocs > 0); @@ -902,7 +901,7 @@ struct run_test // boundary instead; the inner task and the parent still come down. void testClosedInnerExecutorDestroysBoundary() { - std::queue q, iq; + std::queue q, iq; bool closed = false; int work = 0, child_down = 0, parent_down = 0; parked slot; @@ -926,7 +925,7 @@ struct run_test BOOST_TEST(slot); closed = true; - capy::abandon(slot); + slot.reset(); BOOST_TEST_EQ(child_down, 1); BOOST_TEST(iq.empty()); BOOST_TEST_EQ(parent_down, 0); @@ -941,7 +940,7 @@ struct run_test // it still destroys the parent. void testDrainedUnwindDestroysParent() { - std::queue q; + std::queue q; int work = 0, child_down = 0, parent_down = 0, n = 0; parked slot; counting_queue_executor caller{&q, &work}; @@ -957,10 +956,10 @@ struct run_test }; run_async(caller)(parent(destroy_count_t(parent_down))); pump(q); - capy::abandon(slot); + slot.reset(); BOOST_TEST_EQ(child_down, 1); BOOST_TEST_EQ(q.size(), 1u); - capy::abandon(q.front()); + q.front().reset(); q.pop(); BOOST_TEST_EQ(parent_down, 1); BOOST_TEST_EQ(work, 0); @@ -971,7 +970,7 @@ struct run_test // resumed. void testRunHoldsCallerWork() { - std::queue q; + std::queue q; int work = 0, n = 0; parked slot; counting_queue_executor caller{&q, &work}; @@ -990,7 +989,7 @@ struct run_test slot.resume(); // child finishes, parent posted BOOST_TEST_EQ(work, 2); // still held while the parent is queued BOOST_TEST_EQ(q.size(), 1u); - q.front().h.resume(); // parent resumes, run(ex) releases + q.front().resume(); // parent resumes, run(ex) releases q.pop(); BOOST_TEST_EQ(work, 0); pump(q); @@ -1001,7 +1000,7 @@ struct run_test // still releases run(ex)'s hold. void testDrainedParentReleasesWork() { - std::queue q; + std::queue q; int work = 0, parent_down = 0, n = 0; parked slot; counting_queue_executor caller{&q, &work}; @@ -1018,7 +1017,7 @@ struct run_test pump(q); slot.resume(); BOOST_TEST_EQ(q.size(), 1u); - capy::abandon(q.front()); + q.front().reset(); q.pop(); pump(q); BOOST_TEST_EQ(parent_down, 1); @@ -1037,11 +1036,11 @@ struct run_test } void on_work_started() const noexcept {} void on_work_finished() const noexcept {} - std::coroutine_handle<> dispatch(continuation&) const + std::coroutine_handle<> dispatch(coro_chain&&) const { throw std::runtime_error("dispatch"); } - void post(continuation&) const + void post(coro_chain&&) const { throw std::runtime_error("post"); } @@ -1053,11 +1052,12 @@ struct run_test // so inside a task the throw terminates instead. void testRunExPostThrows() { - std::queue q; + std::queue q; int work = 0, child_down = 0; bool caught = false; counting_queue_executor caller{&q, &work}; - await_context env{executor_ref(caller), {}, nullptr}; + chain_state st; + await_context env{executor_ref(caller), {}, nullptr, &st}; auto child = [](destroy_count_t) -> task { co_return; }; { auto aw = capy::run(throwing_post_executor{})( @@ -1087,7 +1087,8 @@ struct run_test { int n = 0; test_executor caller(n); - await_context env{executor_ref(caller), {}, nullptr}; + chain_state st; + await_context env{executor_ref(caller), {}, nullptr, &st}; auto t = parent(); t.handle().promise().set_environment(&env); t.handle().resume(); diff --git a/test/unit/ex/run_async.cpp b/test/unit/ex/run_async.cpp index 6cce7e2fd..4f0668fce 100644 --- a/test/unit/ex/run_async.cpp +++ b/test/unit/ex/run_async.cpp @@ -12,7 +12,6 @@ #include #include -#include #include #include @@ -92,16 +91,16 @@ struct sync_executor void on_work_started() const noexcept {} void on_work_finished() const noexcept {} - std::coroutine_handle<> dispatch(continuation& c) const + std::coroutine_handle<> dispatch(coro_chain&& c) const { if(dispatch_count_) ++(*dispatch_count_); - return c.h; + return c.release_handle(); } - void post(continuation& c) const + void post(coro_chain&& c) const { - c.h.resume(); + c.resume(); } }; @@ -112,11 +111,11 @@ static_assert(Executor); /// Queuing executor - queues for manual execution. struct queue_executor { - std::queue* queue_; + std::queue* queue_; test_io_context* ctx_ = nullptr; static test_io_context default_ctx_; - explicit queue_executor(std::queue& q) + explicit queue_executor(std::queue& q) : queue_(&q) { } @@ -134,15 +133,15 @@ struct queue_executor void on_work_started() const noexcept {} void on_work_finished() const noexcept {} - std::coroutine_handle<> dispatch(continuation& c) const + std::coroutine_handle<> dispatch(coro_chain&& c) const { - queue_->push(c); + queue_->push(std::move(c)); return std::noop_coroutine(); } - void post(continuation& c) const + void post(coro_chain&& c) const { - queue_->push(c); + queue_->push(std::move(c)); } }; @@ -182,12 +181,12 @@ struct refusing_executor void on_work_started() const noexcept { ++*work_; } void on_work_finished() const noexcept { --*work_; } - std::coroutine_handle<> dispatch(continuation&) const + std::coroutine_handle<> dispatch(coro_chain&&) const { throw_test_exception("dispatch"); } - void post(continuation&) const + void post(coro_chain&&) const { throw_test_exception("post"); } @@ -335,7 +334,7 @@ struct run_async_test alloc_counts st; int task_down = 0, handler_down = 0; { - std::queue q; + std::queue q; queuing_executor ex(q); auto probe = [](destroy_count_t) -> task { co_return; }; run_async(ex, counting_allocator(st), @@ -343,9 +342,9 @@ struct run_async_test [](std::exception_ptr) { BOOST_TEST(false); })( probe(destroy_count_t(task_down))); BOOST_TEST_EQ(q.size(), 1u); - auto h = q.front(); + auto h = std::move(q.front()); q.pop(); - capy::abandon(h); + h.reset(); pump(q); } BOOST_TEST_EQ(task_down, 1); @@ -360,7 +359,7 @@ struct run_async_test int task_down = 0, handler_down = 0; lease_resource mr; { - std::queue q; + std::queue q; queuing_executor ex(q); auto probe = [](destroy_count_t) -> task { co_return; }; run_async(ex, &mr, @@ -371,9 +370,9 @@ struct run_async_test [](std::exception_ptr) { BOOST_TEST(false); })( probe(destroy_count_t(task_down))); BOOST_TEST_EQ(q.size(), 1u); - auto h = q.front(); + auto h = std::move(q.front()); q.pop(); - capy::abandon(h); + h.reset(); pump(q); } BOOST_TEST_EQ(task_down, 1); @@ -740,7 +739,7 @@ struct run_async_test // Three tasks on the same executor: one with a scoped stop token, // two with the default (empty) token. Cancelling the scoped token // should only affect that task, not the others. - std::queue queue; + std::queue queue; queue_executor d(queue); bool default_1_stopped = true; @@ -764,9 +763,9 @@ struct run_async_test while(!queue.empty()) { - auto h = queue.front().h; + auto c = std::move(queue.front()); queue.pop(); - h.resume(); + c.resume(); } BOOST_TEST(!default_1_stopped); @@ -883,7 +882,7 @@ struct run_async_test void testAsyncDispatcherBasic() { - std::queue queue; + std::queue queue; queue_executor d(queue); int result = 0; @@ -896,9 +895,9 @@ struct run_async_test // Execute the queued work while(!queue.empty()) { - auto h = queue.front().h; + auto c = std::move(queue.front()); queue.pop(); - h.resume(); + c.resume(); } BOOST_TEST_EQ(result, 42); @@ -907,7 +906,7 @@ struct run_async_test void testAsyncDispatcherMultiple() { - std::queue queue; + std::queue queue; queue_executor d(queue); int sum = 0; @@ -921,9 +920,9 @@ struct run_async_test // Execute all while(!queue.empty()) { - auto h = queue.front().h; + auto c = std::move(queue.front()); queue.pop(); - h.resume(); + c.resume(); } BOOST_TEST_EQ(sum, 126); diff --git a/test/unit/ex/run_blocking.cpp b/test/unit/ex/run_blocking.cpp index 3aee026d3..27882b42f 100644 --- a/test/unit/ex/run_blocking.cpp +++ b/test/unit/ex/run_blocking.cpp @@ -52,9 +52,9 @@ namespace { struct posts_on_destroy { blocking_executor ex; - continuation* c; + coro_chain* c; - posts_on_destroy(blocking_executor e, continuation* cc) noexcept + posts_on_destroy(blocking_executor e, coro_chain* cc) noexcept : ex(e) , c(cc) { @@ -69,7 +69,7 @@ struct posts_on_destroy ~posts_on_destroy() { if(c) - ex.post(*c); + ex.post(std::move(*c)); } }; @@ -89,9 +89,9 @@ plain_probe(destroy_count_t) struct dtor_poster : execution_context::service { blocking_executor ex_; - continuation* c_; + coro_chain* c_; - dtor_poster(execution_context&, blocking_executor ex, continuation& c) + dtor_poster(execution_context&, blocking_executor ex, coro_chain& c) : ex_(ex) , c_(&c) { @@ -99,7 +99,7 @@ struct dtor_poster : execution_context::service ~dtor_poster() { - ex_.post(*c_); + ex_.post(std::move(*c_)); } void shutdown() override {} @@ -110,12 +110,12 @@ struct dtor_poster : execution_context::service struct shutdown_poster : execution_context::service { blocking_executor ex_; - std::vector* cs_; + std::vector* cs_; shutdown_poster( execution_context&, blocking_executor ex, - std::vector& cs) + std::vector& cs) : ex_(ex) , cs_(&cs) { @@ -126,7 +126,7 @@ struct shutdown_poster : execution_context::service std::thread t([this] { for(auto& c : *cs_) - ex_.post(c); + ex_.post(std::move(c)); }); t.join(); } @@ -136,12 +136,12 @@ struct shutdown_poster : execution_context::service struct shutdown_dispatcher : execution_context::service { blocking_executor ex_; - continuation* c_; + coro_chain* c_; shutdown_dispatcher( execution_context&, blocking_executor ex, - continuation& c) + coro_chain& c) : ex_(ex) , c_(&c) { @@ -149,7 +149,7 @@ struct shutdown_dispatcher : execution_context::service void shutdown() override { - safe_resume(ex_.dispatch(*c_)); + safe_resume(ex_.dispatch(std::move(*c_))); } }; @@ -158,9 +158,9 @@ struct shutdown_dispatcher : execution_context::service struct late_poster : execution_context::service { blocking_executor ex_; - continuation* c_; + coro_chain* c_; - late_poster(execution_context&, blocking_executor ex, continuation& c) + late_poster(execution_context&, blocking_executor ex, coro_chain& c) : ex_(ex) , c_(&c) { @@ -168,7 +168,7 @@ struct late_poster : execution_context::service void shutdown() override { - ex_.post(*c_); + ex_.post(std::move(*c_)); } }; @@ -204,9 +204,9 @@ struct teardown_witness : execution_context::service struct poster_maker { blocking_context* ctx; - continuation* c; + coro_chain* c; - poster_maker(blocking_context& x, continuation& cont) noexcept + poster_maker(blocking_context& x, coro_chain& cont) noexcept : ctx(&x) , c(&cont) { @@ -496,12 +496,13 @@ struct run_blocking_test int down = 0; auto probe = [](destroy_count_t) -> task { co_return; }; auto t = probe(destroy_count_t(down)); - auto h = t.handle(); + chain_state st; + st.bind_root(t.handle()); + st.arm_root(); t.release(); { blocking_context ctx; - continuation c{h}; - ctx.get_executor().post(c); + ctx.get_executor().post(coro_chain::from_address(&st)); } BOOST_TEST_EQ(down, 1); } @@ -514,12 +515,15 @@ struct run_blocking_test constexpr int n = 16; int down = 0; auto probe = [](destroy_count_t) -> task { co_return; }; - std::vector cs; + std::vector sts(n); + std::vector cs; cs.reserve(n); for(int i = 0; i < n; ++i) { auto t = probe(destroy_count_t(down)); - cs.push_back(continuation{t.handle()}); + sts[i].bind_root(t.handle()); + sts[i].arm_root(); + cs.push_back(coro_chain::from_address(&sts[i])); t.release(); } { @@ -542,7 +546,10 @@ struct run_blocking_test co_return; }; auto t = probe(destroy_count_t(down), ran); - continuation c{t.handle()}; + chain_state st; + st.bind_root(t.handle()); + st.arm_root(); + auto c = coro_chain::from_address(&st); t.release(); { blocking_context ctx; @@ -584,7 +591,10 @@ struct run_blocking_test { int down = 0; auto t = plain_probe(destroy_count_t(down)); - continuation c{t.handle()}; + chain_state st; + st.bind_root(t.handle()); + st.arm_root(); + auto c = coro_chain::from_address(&st); t.release(); { blocking_context ctx; @@ -604,13 +614,19 @@ struct run_blocking_test int seen = -1; auto maker = [](poster_maker) -> task { co_return; }; auto t = plain_probe(destroy_count_t(down)); - continuation probe_c{t.handle()}; + chain_state probe_st; + probe_st.bind_root(t.handle()); + probe_st.arm_root(); + auto probe_c = coro_chain::from_address(&probe_st); t.release(); - continuation maker_c; + chain_state maker_st; + coro_chain maker_c; { blocking_context ctx; auto m = maker(poster_maker(ctx, probe_c)); - maker_c.h = m.handle(); + maker_st.bind_root(m.handle()); + maker_st.arm_root(); + maker_c = coro_chain::from_address(&maker_st); m.release(); ctx.make_service(ctx.get_executor(), maker_c); ctx.make_service(down, seen); @@ -629,20 +645,23 @@ struct run_blocking_test // Outlives the context, so the queued work is given up by the // context's shutdown rather than by the strand's destructor. std::optional> s; - continuation c1; - continuation c2; + chain_state st1, st2; + coro_chain c2; { blocking_context ctx; auto ex = ctx.get_executor(); s.emplace(ex); auto t2 = plain_probe(destroy_count_t(posted_down)); - c2.h = t2.handle(); + st2.bind_root(t2.handle()); + st2.arm_root(); t2.release(); + c2 = coro_chain::from_address(&st2); auto t1 = posting_probe( destroy_count_t(down), posts_on_destroy(ex, &c2)); - c1.h = t1.handle(); + st1.bind_root(t1.handle()); + st1.arm_root(); t1.release(); - s->post(c1); + s->post(coro_chain::from_address(&st1)); } s.reset(); BOOST_TEST_EQ(down, 1); diff --git a/test/unit/ex/run_priority.cpp b/test/unit/ex/run_priority.cpp index 23ece390e..65c610d6c 100644 --- a/test/unit/ex/run_priority.cpp +++ b/test/unit/ex/run_priority.cpp @@ -43,11 +43,14 @@ struct log_coro { std::vector* log; std::string msg; + chain_state chain_; log_coro get_return_object() noexcept { - return log_coro{ - std::coroutine_handle::from_promise(*this)}; + auto h = std::coroutine_handle::from_promise(*this); + chain_.bind_root(h); + chain_.arm_root(); + return log_coro{h}; } std::suspend_always initial_suspend() noexcept { return {}; } @@ -66,6 +69,12 @@ struct log_coro void release() noexcept { h_ = nullptr; } + coro_chain take_chain() noexcept + { + auto h = std::exchange(h_, nullptr); + return coro_chain::from_address(&h.promise().chain_); + } + private: explicit log_coro(std::coroutine_handle h) : h_(h) {} }; @@ -88,7 +97,7 @@ struct run_priority_test void testForwardCrossing() { - std::queue q; + std::queue q; queuing_executor qe(q); test::priority_executor_state state; test::priority_executor pe(state, qe); @@ -110,9 +119,7 @@ struct run_priority_test run_async(pe, [&]() { outer_done = true; })(outer_task_fn()); auto sibling_coro = make_log_coro(log, "sibling"); - continuation sibling_cont{sibling_coro.handle()}; - pe.post(sibling_cont); - sibling_coro.release(); + pe.post(sibling_coro.take_chain()); pump(q); @@ -135,7 +142,7 @@ struct run_priority_test void testReturnTripParentWrongFrame() { - std::queue q; + std::queue q; queuing_executor qe(q); test::priority_executor_state state; test::priority_executor pe(state, qe); @@ -151,9 +158,7 @@ struct run_priority_test log.push_back("outer_start"); auto pending_high_coro = make_log_coro(log, "pending_high"); - continuation pending_high_cont{pending_high_coro.handle()}; - pe.post_high(pending_high_cont); - pending_high_coro.release(); + pe.post_high(pending_high_coro.take_chain()); int dummy = 0; test_executor inline_ex(1, dummy); @@ -184,7 +189,7 @@ struct run_priority_test void testExitStrandOverPriority() { - std::queue q; + std::queue q; queuing_executor qe(q); test::priority_executor_state state; test::priority_executor pe(state, qe); diff --git a/test/unit/ex/strand.cpp b/test/unit/ex/strand.cpp index b0e3d0cab..de6a619a0 100644 --- a/test/unit/ex/strand.cpp +++ b/test/unit/ex/strand.cpp @@ -16,7 +16,6 @@ #include #include -#include #include #include #include @@ -52,7 +51,7 @@ static_assert(Executor>, // Fails its next posts, running a hook in each failing post first. struct reentrant_executor { - std::queue* q_; + std::queue* q_; test_io_context* ctx_; int* fails_; std::function* on_fail_; @@ -64,12 +63,12 @@ struct reentrant_executor test_io_context& context() const noexcept { return *ctx_; } void on_work_started() const noexcept {} void on_work_finished() const noexcept {} - std::coroutine_handle<> dispatch(continuation& c) const + std::coroutine_handle<> dispatch(coro_chain&& c) const { - post(c); + post(std::move(c)); return std::noop_coroutine(); } - void post(continuation& c) const + void post(coro_chain&& c) const { if(*fails_ > 0) { @@ -78,7 +77,7 @@ struct reentrant_executor std::exchange(*on_fail_, nullptr)(); throw std::runtime_error("post"); } - q_->push(c); + q_->push(std::move(c)); } }; @@ -88,11 +87,15 @@ struct counter_coro struct promise_type { std::atomic* counter; + chain_state chain_; counter_coro get_return_object() noexcept { - return counter_coro{std::coroutine_handle::from_promise(*this)}; + auto h = std::coroutine_handle::from_promise(*this); + chain_.bind_root(h); + chain_.arm_root(); + return counter_coro{h}; } std::suspend_always @@ -154,6 +157,19 @@ struct counter_coro h_ = nullptr; } + coro_chain + take_chain() noexcept + { + auto h = std::exchange(h_, nullptr); + return coro_chain::from_address(&h.promise().chain_); + } + + coro_chain + peek_chain() noexcept + { + return coro_chain::from_address(&h_.promise().chain_); + } + private: explicit counter_coro(std::coroutine_handle h) : h_(h) @@ -179,11 +195,15 @@ struct order_coro std::vector* log; std::mutex* log_mutex; int id; + chain_state chain_; order_coro get_return_object() noexcept { - return order_coro{std::coroutine_handle::from_promise(*this)}; + auto h = std::coroutine_handle::from_promise(*this); + chain_.bind_root(h); + chain_.arm_root(); + return order_coro{h}; } std::suspend_always @@ -245,6 +265,13 @@ struct order_coro h_ = nullptr; } + coro_chain + take_chain() noexcept + { + auto h = std::exchange(h_, nullptr); + return coro_chain::from_address(&h.promise().chain_); + } + private: explicit order_coro(std::coroutine_handle h) : h_(h) @@ -267,11 +294,15 @@ struct lifetime_coro { struct promise_type { + chain_state chain_; + lifetime_coro get_return_object() noexcept { - return lifetime_coro{ - std::coroutine_handle::from_promise(*this)}; + auto h = std::coroutine_handle::from_promise(*this); + chain_.bind_root(h); + chain_.arm_root(); + return lifetime_coro{h}; } std::suspend_always initial_suspend() noexcept { return {}; } std::suspend_never final_suspend() noexcept { return {}; } @@ -294,6 +325,13 @@ struct lifetime_coro std::coroutine_handle handle() const noexcept { return h_; } void release() noexcept { h_ = nullptr; } + coro_chain + take_chain() noexcept + { + auto h = std::exchange(h_, nullptr); + return coro_chain::from_address(&h.promise().chain_); + } + private: explicit lifetime_coro(std::coroutine_handle h) : h_(h) {} friend lifetime_coro make_lifetime_coro(std::atomic&); @@ -459,11 +497,15 @@ struct strand_test { struct promise_type { + chain_state chain_; + latched_coro get_return_object() noexcept { - return latched_coro{ - std::coroutine_handle::from_promise(*this)}; + auto h = std::coroutine_handle::from_promise(*this); + chain_.bind_root(h); + chain_.arm_root(); + return latched_coro{h}; } std::suspend_always initial_suspend() noexcept { return {}; } std::suspend_never final_suspend() noexcept { return {}; } @@ -471,6 +513,12 @@ struct strand_test void unhandled_exception() { std::terminate(); } }; std::coroutine_handle h_; + + coro_chain take_chain() noexcept + { + auto h = std::exchange(h_, nullptr); + return coro_chain::from_address(&h.promise().chain_); + } }; auto make_latched = @@ -486,18 +534,14 @@ struct strand_test auto coro_a = make_latched( &a_started, a_done, std::chrono::milliseconds(200)); - continuation ca{coro_a.h_}; - sA.post(ca); - coro_a.h_ = nullptr; + sA.post(coro_a.take_chain()); // Wait until A is actively sleeping BOOST_TEST(wait_for([&]{ return a_started.load(); })); auto coro_b = make_latched( nullptr, b_done, std::chrono::milliseconds(0)); - continuation cb{coro_b.h_}; - sB.post(cb); - coro_b.h_ = nullptr; + sB.post(coro_b.take_chain()); // B should complete while A is still sleeping BOOST_TEST(wait_for( @@ -516,16 +560,11 @@ struct strand_test std::atomic done{false}; std::weak_ptr impl_weak; - // c must outlive its time in the strand queue; the strand - // links it intrusively rather than copying. - continuation c; { auto s = strand(pool.get_executor()); impl_weak = s.impl_; auto coro = make_lifetime_coro(done); - c.h = coro.handle(); - s.post(c); - coro.release(); + s.post(coro.take_chain()); } // strand handle dropped here BOOST_TEST(wait_for([&]{ return done.load(); })); @@ -548,19 +587,12 @@ struct strand_test for(int i = 0; i < num_strands; ++i) strands.push_back(strand(pool.get_executor())); - std::vector coros; - coros.reserve(num_strands * posts_per_strand); - std::vector conts; - conts.reserve(num_strands * posts_per_strand); - for(int i = 0; i < num_strands; ++i) { for(int j = 0; j < posts_per_strand; ++j) { - coros.push_back(make_counter_coro(total)); - conts.push_back({coros.back().handle()}); - strands[i].post(conts.back()); - coros.back().release(); + auto coro = make_counter_coro(total); + strands[i].post(coro.take_chain()); } } @@ -637,12 +669,8 @@ struct strand_test auto coroA = make_busy(); auto coroB = make_busy(); - continuation cA{coroA.handle()}; - continuation cB{coroB.handle()}; - sA.post(cA); - sB.post(cB); - coroA.release(); - coroB.release(); + sA.post(coroA.take_chain()); + sB.post(coroB.take_chain()); BOOST_TEST(wait_for( [&]{ return done.load() >= 2; }, @@ -669,9 +697,7 @@ struct strand_test std::atomic counter{0}; auto coro = make_counter_coro(counter); - continuation c{coro.handle()}; - s.post(c); - coro.release(); + s.post(coro.take_chain()); BOOST_TEST(wait_for([&]{ return counter.load() >= 1; })); BOOST_TEST_EQ(counter.load(), 1); @@ -686,9 +712,7 @@ struct strand_test std::atomic counter{0}; auto coro = make_counter_coro(counter); - continuation c{coro.handle()}; - s.dispatch(c); - coro.release(); + s.dispatch(coro.take_chain()); BOOST_TEST(wait_for([&]{ return counter.load() >= 1; })); BOOST_TEST_EQ(counter.load(), 1); @@ -703,17 +727,10 @@ struct strand_test std::atomic counter{0}; constexpr int N = 100; - std::vector coros; - coros.reserve(N); - std::vector conts; - conts.reserve(N); - for(int i = 0; i < N; ++i) { - coros.push_back(make_counter_coro(counter)); - conts.push_back({coros.back().handle()}); - s.post(conts.back()); - coros.back().release(); + auto coro = make_counter_coro(counter); + s.post(coro.take_chain()); } BOOST_TEST(wait_for([&]{ return counter.load() >= N; })); @@ -733,29 +750,15 @@ struct strand_test std::vector threads; threads.reserve(num_threads); - // Storage hoisted out of the threads so each continuation - // outlives its time in the strand queue. - std::vector> coros_per_thread(num_threads); - std::vector> conts_per_thread(num_threads); - for(int i = 0; i < num_threads; ++i) - { - coros_per_thread[i].reserve(per_thread); - conts_per_thread[i].reserve(per_thread); - } - for(int i = 0; i < num_threads; ++i) { threads.emplace_back( - [&s, &counter, - &my_coros = coros_per_thread[i], - &my_conts = conts_per_thread[i]] + [&s, &counter] { for(int j = 0; j < per_thread; ++j) { - my_coros.push_back(make_counter_coro(counter)); - my_conts.push_back({my_coros.back().handle()}); - s.post(my_conts.back()); - my_coros.back().release(); + auto coro = make_counter_coro(counter); + s.post(coro.take_chain()); } }); } @@ -778,18 +781,11 @@ struct strand_test std::mutex log_mutex; constexpr int N = 50; - std::vector coros; - coros.reserve(N); - std::vector conts; - conts.reserve(N); - // Post coroutines with sequential IDs for(int i = 0; i < N; ++i) { - coros.push_back(make_order_coro(log, log_mutex, i)); - conts.push_back({coros.back().handle()}); - s.post(conts.back()); - coros.back().release(); + auto coro = make_order_coro(log, log_mutex, i); + s.post(coro.take_chain()); } BOOST_TEST(wait_for([&]{ @@ -821,11 +817,15 @@ struct strand_test { struct promise_type { + chain_state chain_; + tracking_coro get_return_object() noexcept { - return tracking_coro{ - std::coroutine_handle::from_promise(*this)}; + auto h = std::coroutine_handle::from_promise(*this); + chain_.bind_root(h); + chain_.arm_root(); + return tracking_coro{h}; } std::suspend_always initial_suspend() noexcept { return {}; } @@ -861,6 +861,12 @@ struct strand_test void release() noexcept { h_ = nullptr; } + coro_chain take_chain() noexcept + { + auto h = std::exchange(h_, nullptr); + return coro_chain::from_address(&h.promise().chain_); + } + private: explicit tracking_coro(std::coroutine_handle h) : h_(h) @@ -883,17 +889,10 @@ struct strand_test co_return; }; - std::vector coros; - coros.reserve(N); - std::vector conts; - conts.reserve(N); - for(int i = 0; i < N; ++i) { - coros.push_back(make_tracking_coro()); - conts.push_back({coros.back().handle()}); - s.post(conts.back()); - coros.back().release(); + auto coro = make_tracking_coro(); + s.post(coro.take_chain()); } BOOST_TEST(wait_for([&]{ return completed.load() >= N; })); @@ -956,17 +955,10 @@ struct strand_test std::atomic counter{0}; constexpr int N = 20; - std::vector coros; - coros.reserve(N); - std::vector conts; - conts.reserve(N); - for(int i = 0; i < N; ++i) { - coros.push_back(make_counter_coro(counter)); - conts.push_back({coros.back().handle()}); - s.post(conts.back()); - coros.back().release(); + auto coro = make_counter_coro(counter); + s.post(coro.take_chain()); } BOOST_TEST(wait_for([&]{ return counter.load() >= N; })); @@ -991,8 +983,7 @@ struct strand_test alloc_counts st; int child_down = 0, parent_down = 0; parked slot; - continuation c; - std::queue q; + std::queue q; { auto ctx = std::make_unique(); queuing_executor qe(q); @@ -1012,12 +1003,11 @@ struct strand_test pump(q); BOOST_TEST(slot); - c = slot; - s.post(c); + s.post(slot.take()); // The strand's runner is lost; the chain stays queued. while(!q.empty()) { - capy::abandon(q.front()); + q.front().reset(); q.pop(); } BOOST_TEST_EQ(parent_down, 0); @@ -1035,13 +1025,14 @@ struct strand_test testShutdownDestroysQueuedAcrossStrands() { int down[4] = {}; - continuation conts[4] = {}; - std::queue q; + chain_state states[4]; + std::queue q; auto probe = [](destroy_count_t) -> task { co_return; }; for(std::size_t i = 0; i < 4; ++i) { auto t = probe(destroy_count_t(down[i])); - conts[i].h = t.handle(); + states[i].bind_root(t.handle()); + states[i].arm_root(); t.release(); } auto ctx = std::make_unique(); @@ -1049,14 +1040,14 @@ struct strand_test qe.ctx_ = ctx.get(); strand s1{qe}; strand s2{qe}; - s1.post(conts[0]); - s1.post(conts[1]); - s2.post(conts[2]); - s2.post(conts[3]); + s1.post(coro_chain::from_address(&states[0])); + s1.post(coro_chain::from_address(&states[1])); + s2.post(coro_chain::from_address(&states[2])); + s2.post(coro_chain::from_address(&states[3])); BOOST_TEST_EQ(q.size(), 2u); while(!q.empty()) { - capy::abandon(q.front()); + q.front().reset(); q.pop(); } for(int d : down) @@ -1074,23 +1065,24 @@ struct strand_test testShutdownLeavesNothingForStrandDestructor() { int down[2] = {}; - continuation conts[2] = {}; - std::queue q; + chain_state states[2]; + std::queue q; auto probe = [](destroy_count_t) -> task { co_return; }; for(std::size_t i = 0; i < 2; ++i) { auto t = probe(destroy_count_t(down[i])); - conts[i].h = t.handle(); + states[i].bind_root(t.handle()); + states[i].arm_root(); t.release(); } auto ctx = std::make_unique(); queuing_executor qe(q); qe.ctx_ = ctx.get(); auto s = std::make_unique>(qe); - s->post(conts[0]); - s->post(conts[1]); + s->post(coro_chain::from_address(&states[0])); + s->post(coro_chain::from_address(&states[1])); BOOST_TEST_EQ(q.size(), 1u); - capy::abandon(q.front()); + q.front().reset(); q.pop(); for(int d : down) BOOST_TEST_EQ(d, 0); @@ -1129,7 +1121,7 @@ struct strand_test struct locked_queue { std::mutex m; - std::vector v; + std::vector v; }; struct locked_executor { @@ -1143,15 +1135,15 @@ struct strand_test test_io_context& context() const noexcept { return *ctx_; } void on_work_started() const noexcept {} void on_work_finished() const noexcept {} - std::coroutine_handle<> dispatch(continuation& c) const + std::coroutine_handle<> dispatch(coro_chain&& c) const { - post(c); + post(std::move(c)); return std::noop_coroutine(); } - void post(continuation& c) const + void post(coro_chain&& c) const { std::lock_guard lk(q_->m); - q_->v.push_back(c); + q_->v.push_back(std::move(c)); } }; auto probe = [](destroy_count_t) -> task { co_return; }; @@ -1163,22 +1155,22 @@ struct strand_test locked_executor le{&q, ctx.get()}; auto s = std::make_unique>(le); auto t = probe(destroy_count_t(down)); - continuation c{t.handle()}; + chain_state st; + st.bind_root(t.handle()); + st.arm_root(); t.release(); std::atomic go{0}; std::thread a([&]{ go.fetch_add(1); while(go.load() < 2) std::this_thread::yield(); - s->post(c); + s->post(coro_chain::from_address(&st)); }); go.fetch_add(1); while(go.load() < 2) std::this_thread::yield(); ctx->shutdown(); a.join(); - for(auto& queued : q.v) - capy::abandon(queued); q.v.clear(); s.reset(); ctx.reset(); @@ -1193,7 +1185,7 @@ struct strand_test { struct throwing_executor { - std::queue* q_; + std::queue* q_; test_io_context* ctx_; bool* fail_; @@ -1204,37 +1196,37 @@ struct strand_test test_io_context& context() const noexcept { return *ctx_; } void on_work_started() const noexcept {} void on_work_finished() const noexcept {} - std::coroutine_handle<> dispatch(continuation& c) const + std::coroutine_handle<> dispatch(coro_chain&& c) const { - post(c); + post(std::move(c)); return std::noop_coroutine(); } - void post(continuation& c) const + void post(coro_chain&& c) const { if(*fail_) throw std::runtime_error("post"); - q_->push(c); + q_->push(std::move(c)); } }; std::atomic ran{0}; - std::queue q; + std::queue q; bool fail = true; auto held = make_counter_coro(ran); auto ctx = std::make_unique(); auto s = std::make_unique>( throwing_executor{&q, ctx.get(), &fail}); - continuation c1{held.handle()}; - BOOST_TEST_THROWS(s->post(c1), std::runtime_error); + auto c1 = held.peek_chain(); + BOOST_TEST_THROWS(s->post(std::move(c1)), std::runtime_error); + // c1 was restored on throw; disarm so ~held() destroys it once + std::ignore = c1.release_handle(); fail = false; auto next = make_counter_coro(ran); - continuation c2{next.handle()}; - next.release(); - s->post(c2); + s->post(next.take_chain()); while(!q.empty()) { - auto c = q.front(); + auto c = std::move(q.front()); q.pop(); - c.h.resume(); + c.resume(); } BOOST_TEST_EQ(ran.load(), 1); s.reset(); @@ -1250,7 +1242,7 @@ struct strand_test auto attempt = [](int fails, int& ran, int& down) { std::atomic count{0}; - std::queue q; + std::queue q; std::function on_fail; auto held = make_counter_coro(count); auto behind = [](std::atomic* n, destroy_count_t) @@ -1259,19 +1251,19 @@ struct strand_test ++*n; co_return; }(&count, destroy_count_t(down)); - continuation c1{held.handle()}; - continuation c2{behind.handle()}; - behind.release(); + auto c1 = held.peek_chain(); + auto c2 = behind.take_chain(); auto ctx = std::make_unique(); auto s = std::make_unique>( reentrant_executor{&q, ctx.get(), &fails, &on_fail}); - on_fail = [&] { s->post(c2); }; - BOOST_TEST_THROWS(s->post(c1), std::runtime_error); + on_fail = [&] { s->post(std::move(c2)); }; + BOOST_TEST_THROWS(s->post(std::move(c1)), std::runtime_error); + std::ignore = c1.release_handle(); while(!q.empty()) { - auto c = q.front(); + auto c = std::move(q.front()); q.pop(); - c.h.resume(); + c.resume(); } ran = count.load(); s.reset(); @@ -1300,11 +1292,13 @@ struct strand_test { int down = 0; int fails = 1; - std::queue q; + std::queue q; std::function on_fail; auto probe = [](destroy_count_t) -> task { co_return; }; auto t = probe(destroy_count_t(down)); - continuation c{t.handle()}; + chain_state st; + st.bind_root(t.handle()); + st.arm_root(); t.release(); auto ctx = std::make_unique(); auto s = std::make_unique>( @@ -1313,7 +1307,7 @@ struct strand_test bool threw = false; try { - s->post(c); + s->post(coro_chain::from_address(&st)); } catch(std::runtime_error const&) { @@ -1334,24 +1328,30 @@ struct strand_test { int held_down = 0, behind_down = 0; int fails = 2; - std::queue q; + std::queue q; std::function on_fail; auto probe = [](destroy_count_t) -> task { co_return; }; { auto held = probe(destroy_count_t(held_down)); auto behind = probe(destroy_count_t(behind_down)); - continuation c1{held.handle()}; - continuation c2{behind.handle()}; + chain_state st1, st2; + st1.bind_root(held.handle()); + st1.arm_root(); + held.release(); + st2.bind_root(behind.handle()); + st2.arm_root(); behind.release(); + coro_chain c1 = coro_chain::from_address(&st1); + coro_chain c2 = coro_chain::from_address(&st2); auto ctx = std::make_unique(); auto s = std::make_unique>( reentrant_executor{&q, ctx.get(), &fails, &on_fail}); on_fail = [&] { - s->post(c2); + s->post(std::move(c2)); on_fail = [&] { ctx->shutdown(); }; }; - BOOST_TEST_THROWS(s->post(c1), std::runtime_error); + BOOST_TEST_THROWS(s->post(std::move(c1)), std::runtime_error); BOOST_TEST_EQ(held_down, 0); BOOST_TEST_EQ(behind_down, 1); BOOST_TEST(q.empty()); @@ -1368,10 +1368,12 @@ struct strand_test testStrandCreatedAfterShutdownIsClosed() { int down = 0; - std::queue q; + std::queue q; auto probe = [](destroy_count_t) -> task { co_return; }; auto t = probe(destroy_count_t(down)); - continuation c{t.handle()}; + chain_state st; + st.bind_root(t.handle()); + st.arm_root(); t.release(); auto ctx = std::make_unique(); queuing_executor qe(q); @@ -1379,7 +1381,7 @@ struct strand_test strand before{qe}; ctx->shutdown(); auto after = std::make_unique>(qe); - after->post(c); + after->post(coro_chain::from_address(&st)); BOOST_TEST_EQ(down, 1); BOOST_TEST(q.empty()); ctx.reset(); @@ -1392,17 +1394,19 @@ struct strand_test testStrandServiceCreatedAfterShutdown() { int down = 0; - std::queue q; + std::queue q; auto probe = [](destroy_count_t) -> task { co_return; }; auto t = probe(destroy_count_t(down)); - continuation c{t.handle()}; + chain_state st; + st.bind_root(t.handle()); + st.arm_root(); t.release(); auto ctx = std::make_unique(); queuing_executor qe(q); qe.ctx_ = ctx.get(); ctx->shutdown(); auto s = std::make_unique>(qe); - s->post(c); + s->post(coro_chain::from_address(&st)); BOOST_TEST_EQ(down, 1); BOOST_TEST(q.empty()); ctx.reset(); @@ -1418,9 +1422,9 @@ struct strand_test down = 0; struct older_service : execution_context::service { - std::queue q; + std::queue q; std::optional> s; - continuation c; + chain_state st; explicit older_service(execution_context&) {} @@ -1431,9 +1435,10 @@ struct strand_test co_return; }; auto t = probe(destroy_count_t(down)); - c.h = t.handle(); + st.bind_root(t.handle()); + st.arm_root(); t.release(); - s->post(c); + s->post(coro_chain::from_address(&st)); } void shutdown() override {} @@ -1454,17 +1459,19 @@ struct strand_test testPostAfterShutdownDestroyed() { int down = 0; - std::queue q; + std::queue q; auto probe = [](destroy_count_t) -> task { co_return; }; auto t = probe(destroy_count_t(down)); - continuation c{t.handle()}; + chain_state st; + st.bind_root(t.handle()); + st.arm_root(); t.release(); auto ctx = std::make_unique(); queuing_executor qe(q); qe.ctx_ = ctx.get(); strand s{qe}; ctx->shutdown(); - s.post(c); + s.post(coro_chain::from_address(&st)); BOOST_TEST_EQ(down, 1); BOOST_TEST(q.empty()); } @@ -1475,20 +1482,23 @@ struct strand_test testQueuedCoroutinesDestroyedWithStrand() { int a_down = 0, b_down = 0; - std::queue q; + std::queue q; auto probe = [](destroy_count_t) -> task { co_return; }; auto ta = probe(destroy_count_t(a_down)); auto tb = probe(destroy_count_t(b_down)); - continuation ca{ta.handle()}; - continuation cb{tb.handle()}; + chain_state sa, sb; + sa.bind_root(ta.handle()); + sa.arm_root(); + sb.bind_root(tb.handle()); + sb.arm_root(); ta.release(); tb.release(); { strand s{queuing_executor(q)}; - s.post(ca); - s.post(cb); + s.post(coro_chain::from_address(&sa)); + s.post(coro_chain::from_address(&sb)); BOOST_TEST_EQ(q.size(), 1u); - capy::abandon(q.front()); + q.front().reset(); q.pop(); } BOOST_TEST_EQ(a_down, 1); @@ -1503,7 +1513,7 @@ struct strand_test { int pa_down = 0, pb_down = 0; parked slot_q, slot_f; - std::queue q; + std::queue q; auto qa = [](parked* s) -> task { co_await park_awaitable{s}; @@ -1530,19 +1540,18 @@ struct strand_test run_async(ex)(pa(&slot_q, destroy_count_t(pa_down))); BOOST_TEST(slot_q); - continuation c{slot_q}; { strand s{queuing_executor(q)}; - s.post(c); + s.post(slot_q.take()); BOOST_TEST_EQ(q.size(), 1u); - capy::abandon(q.front()); + q.front().reset(); q.pop(); run_async(ex)(pb(std::move(s), &slot_f, destroy_count_t(pb_down))); } BOOST_TEST(slot_f); BOOST_TEST_EQ(pa_down, 0); - capy::abandon(slot_f); + slot_f.reset(); BOOST_TEST_EQ(pa_down, 1); BOOST_TEST_EQ(pb_down, 1); } @@ -1556,9 +1565,8 @@ struct strand_test constexpr std::size_t count = 64; int parents_down = 0, holder_down = 0; std::array slots{}; - std::array conts{}; parked slot_leaf; - std::queue q; + std::queue q; auto queued = [](parked* s) -> task { co_await park_awaitable{s}; @@ -1588,11 +1596,10 @@ struct strand_test strand s{queuing_executor(q)}; for(std::size_t i = 0; i < count; ++i) { - conts[i] = slots[i]; - s.post(conts[i]); + s.post(slots[i].take()); } BOOST_TEST_EQ(q.size(), 1u); - capy::abandon(q.front()); + q.front().reset(); q.pop(); run_async(ex)(holder( std::move(s), &slot_leaf, destroy_count_t(holder_down))); @@ -1600,7 +1607,7 @@ struct strand_test BOOST_TEST(slot_leaf); BOOST_TEST_EQ(parents_down, 0); - capy::abandon(slot_leaf); + slot_leaf.reset(); BOOST_TEST_EQ(parents_down, static_cast(count)); BOOST_TEST_EQ(holder_down, 1); } diff --git a/test/unit/ex/thread_pool.cpp b/test/unit/ex/thread_pool.cpp index 8c573f681..98f39137d 100644 --- a/test/unit/ex/thread_pool.cpp +++ b/test/unit/ex/thread_pool.cpp @@ -150,12 +150,12 @@ name_checker check_thread_name(name_check_result& result, char const* prefix) struct late_poster : execution_context::service { thread_pool::executor_type ex_; - continuation* c_; + coro_chain* c_; late_poster( execution_context&, thread_pool::executor_type ex, - continuation& c) + coro_chain& c) : ex_(ex) , c_(&c) { @@ -163,7 +163,7 @@ struct late_poster : execution_context::service void shutdown() override { - ex_.post(*c_); + ex_.post(std::move(*c_)); } }; @@ -171,12 +171,12 @@ struct late_poster : execution_context::service struct dtor_poster : execution_context::service { thread_pool::executor_type ex_; - continuation* c_; + coro_chain* c_; dtor_poster( execution_context&, thread_pool::executor_type ex, - continuation& c) + coro_chain& c) : ex_(ex) , c_(&c) { @@ -184,7 +184,7 @@ struct dtor_poster : execution_context::service ~dtor_poster() { - ex_.post(*c_); + ex_.post(std::move(*c_)); } void shutdown() override {} @@ -195,12 +195,12 @@ struct dtor_poster : execution_context::service struct shutdown_poster : execution_context::service { thread_pool::executor_type ex_; - std::vector* cs_; + std::vector* cs_; shutdown_poster( execution_context&, thread_pool::executor_type ex, - std::vector& cs) + std::vector& cs) : ex_(ex) , cs_(&cs) { @@ -211,7 +211,7 @@ struct shutdown_poster : execution_context::service std::thread t([this] { for(auto& c : *cs_) - ex_.post(c); + ex_.post(std::move(c)); }); t.join(); } @@ -249,9 +249,9 @@ struct teardown_witness : execution_context::service struct poster_maker { thread_pool* pool; - continuation* c; + coro_chain* c; - poster_maker(thread_pool& p, continuation& cont) noexcept + poster_maker(thread_pool& p, coro_chain& cont) noexcept : pool(&p) , c(&cont) { @@ -275,9 +275,9 @@ struct poster_maker struct dtor_poster_maker { thread_pool* pool; - continuation* c; + coro_chain* c; - dtor_poster_maker(thread_pool& p, continuation& cont) noexcept + dtor_poster_maker(thread_pool& p, coro_chain& cont) noexcept : pool(&p) , c(&cont) { @@ -308,8 +308,8 @@ struct signal_park std::coroutine_handle<> await_suspend(std::coroutine_handle<> h, await_context const* env) noexcept { - slot->h = h; - slot->owner = env->owner; + slot->chain_ = env->park(h); + slot->raw_h_ = h; parked->release(); return std::noop_coroutine(); } @@ -381,13 +381,14 @@ struct thread_pool_test void testPostWork() { - // continuation must outlive pool (LIFO destruction order) - continuation c{std::noop_coroutine()}; + chain_state st; + st.bind_root(std::noop_coroutine()); + st.arm_root(); thread_pool pool(1); auto ex = pool.get_executor(); // Post a noop coroutine and verify no exceptions - ex.post(c); + ex.post(coro_chain::from_address(&st)); // Basic test: pool constructs and destructs without issue (void)ex; @@ -412,19 +413,20 @@ struct thread_pool_test // From outside any pool, dispatch() posts. auto probe = make_probe(); auto probe_h = probe.handle(); - auto* target = new continuation{probe_h}; + chain_state st; + st.bind_root(probe_h); + st.arm_root(); std::coroutine_handle<> returned; { thread_pool pool(1); auto ex = pool.get_executor(); - returned = ex.dispatch(*target); + returned = ex.dispatch(coro_chain::from_address(&st)); } BOOST_TEST(returned != probe_h); if(returned != probe_h) probe.release(); - delete target; } void @@ -435,10 +437,9 @@ struct thread_pool_test // enqueue the continuation. auto probe = make_probe(); auto probe_h = probe.handle(); - - // Heap-allocated so target outlives the pool if a buggy - // implementation erroneously posts it. - auto* target = new continuation{probe_h}; + chain_state st; + st.bind_root(probe_h); + st.arm_root(); std::atomic done{false}; std::coroutine_handle<> returned; @@ -448,7 +449,7 @@ struct thread_pool_test auto ex = pool.get_executor(); run_async(ex, [&]{ - returned = ex.dispatch(*target); + returned = ex.dispatch(coro_chain::from_address(&st)); done.store(true); })(void_task()); @@ -464,7 +465,6 @@ struct thread_pool_test // the probe_coro dtor does not double-destroy. if(returned != probe_h) probe.release(); - delete target; } void @@ -475,7 +475,9 @@ struct thread_pool_test // symmetric-transfer. auto probe = make_probe(); auto probe_h = probe.handle(); - auto* target = new continuation{probe_h}; + chain_state st; + st.bind_root(probe_h); + st.arm_root(); std::atomic done{false}; std::coroutine_handle<> returned; @@ -487,7 +489,7 @@ struct thread_pool_test auto ex_b = pool_b.get_executor(); run_async(ex_a, [&]{ - returned = ex_b.dispatch(*target); + returned = ex_b.dispatch(coro_chain::from_address(&st)); done.store(true); })(void_task()); @@ -497,7 +499,6 @@ struct thread_pool_test BOOST_TEST(returned != probe_h); if(returned != probe_h) probe.release(); - delete target; } void @@ -540,14 +541,15 @@ struct thread_pool_test void testConcurrentPost() { - // Pre-allocate continuations: must outlive the pool - // (LIFO destruction order). constexpr int num_threads = 8; constexpr int posts_per_thread = 10; - std::vector> all_conts(num_threads); - for(auto& arr : all_conts) - for(auto& c : arr) - c.h = std::noop_coroutine(); + std::vector> all_states(num_threads); + for(auto& arr : all_states) + for(auto& s : arr) + { + s.bind_root(std::noop_coroutine()); + s.arm_root(); + } thread_pool pool(4); auto ex = pool.get_executor(); @@ -559,11 +561,11 @@ struct thread_pool_test for(int i = 0; i < num_threads; ++i) { - threads.emplace_back([&ex, &post_count, conts = all_conts[i].data()]{ + threads.emplace_back([&ex, &post_count, states = all_states[i].data()]{ // Multiple threads posting concurrently for(int j = 0; j < posts_per_thread; ++j) { - ex.post(conts[j]); + ex.post(coro_chain::from_address(&states[j])); ++post_count; } }); @@ -607,9 +609,11 @@ struct thread_pool_test { name_check_result result; auto nc = check_thread_name(result, "capy-pool-"); - continuation c{nc.h}; + chain_state st; + st.bind_root(nc.h); + st.arm_root(); thread_pool pool(1); - pool.get_executor().post(c); + pool.get_executor().post(coro_chain::from_address(&st)); BOOST_TEST(wait_for([&]{ return result.done.load(); })); BOOST_TEST(result.matches.load()); @@ -619,9 +623,11 @@ struct thread_pool_test { name_check_result result; auto nc = check_thread_name(result, "mypool-"); - continuation c{nc.h}; + chain_state st; + st.bind_root(nc.h); + st.arm_root(); thread_pool pool(1, "mypool-"); - pool.get_executor().post(c); + pool.get_executor().post(coro_chain::from_address(&st)); BOOST_TEST(wait_for([&]{ return result.done.load(); })); BOOST_TEST(result.matches.load()); @@ -631,9 +637,11 @@ struct thread_pool_test { name_check_result result; auto nc = check_thread_name(result, "idx-0"); - continuation c{nc.h}; + chain_state st; + st.bind_root(nc.h); + st.arm_root(); thread_pool pool(1, "idx-"); - pool.get_executor().post(c); + pool.get_executor().post(coro_chain::from_address(&st)); BOOST_TEST(wait_for([&]{ return result.done.load(); })); BOOST_TEST(result.matches.load()); @@ -732,7 +740,7 @@ struct thread_pool_test { std::atomic busy{false}; std::atomic release{false}; - std::array conts; + std::array states; thread_pool pool(1); auto ex = pool.get_executor(); @@ -751,8 +759,9 @@ struct thread_pool_test // Queue items that can't be processed yet for(int i = 0; i < 50; ++i) { - conts[i].h = std::noop_coroutine(); - ex.post(conts[i]); + states[i].bind_root(std::noop_coroutine()); + states[i].arm_root(); + ex.post(coro_chain::from_address(&states[i])); } // Release worker, then pool destructs immediately. @@ -915,14 +924,16 @@ struct thread_pool_test { for(int i = 0; i < 200; ++i) { - continuation c{std::noop_coroutine()}; + chain_state st; + st.bind_root(std::noop_coroutine()); + st.arm_root(); thread_pool pool(4); std::atomic go{false}; std::thread t([&]{ while(!go.load()) { } - pool.get_executor().post(c); + pool.get_executor().post(coro_chain::from_address(&st)); }); go.store(true); pool.join(); @@ -1062,7 +1073,7 @@ struct thread_pool_test if(!BOOST_TEST(parked.try_acquire_for(std::chrono::seconds(30)))) return; - capy::abandon(slot); + slot.reset(); pool.join(); BOOST_TEST_EQ(child_down, 1); BOOST_TEST_EQ(parent_down, 1); @@ -1083,14 +1094,19 @@ struct thread_pool_test auto probe = [](destroy_count_t) -> task { co_return; }; auto maker = [](poster_maker) -> task { co_return; }; auto p = probe(destroy_count_t(down)); - continuation probe_c{p.handle()}; + chain_state probe_st, maker_st; + probe_st.bind_root(p.handle()); + probe_st.arm_root(); p.release(); - continuation maker_c; + auto probe_c = coro_chain::from_address(&probe_st); + coro_chain maker_c; { thread_pool pool(1); auto m = maker(poster_maker(pool, probe_c)); - maker_c.h = m.handle(); + maker_st.bind_root(m.handle()); + maker_st.arm_root(); m.release(); + maker_c = coro_chain::from_address(&maker_st); pool.make_service(pool.get_executor(), maker_c); pool.make_service(down, seen); } @@ -1111,13 +1127,18 @@ struct thread_pool_test auto maker = [](dtor_poster_maker) -> task { co_return; }; int down = 0; auto p = probe(destroy_count_t(down)); - continuation probe_c{p.handle()}; + chain_state probe_st, maker_st; + probe_st.bind_root(p.handle()); + probe_st.arm_root(); p.release(); - continuation maker_c; + auto probe_c = coro_chain::from_address(&probe_st); + coro_chain maker_c; thread_pool pool(1); auto m = maker(dtor_poster_maker(pool, probe_c)); - maker_c.h = m.handle(); + maker_st.bind_root(m.handle()); + maker_st.arm_root(); m.release(); + maker_c = coro_chain::from_address(&maker_st); pool.make_service(pool.get_executor(), maker_c); })); } @@ -1133,7 +1154,7 @@ struct thread_pool_test int child_down = 0, parent_down = 0, handler_down = 0; parked slot; std::binary_semaphore parked{0}; - continuation c; + coro_chain c; { thread_pool pool(1); auto child = [&](destroy_count_t) -> task @@ -1151,7 +1172,7 @@ struct thread_pool_test // Bounds a hang, not a timing assertion. if(!BOOST_TEST(parked.try_acquire_for(std::chrono::seconds(30)))) return; - c = slot; + c = slot.take(); pool.make_service(pool.get_executor(), c); } BOOST_TEST_EQ(child_down, 1); @@ -1169,8 +1190,11 @@ struct thread_pool_test int down = 0; auto probe = [](destroy_count_t) -> task { co_return; }; auto t = probe(destroy_count_t(down)); - continuation c{t.handle()}; + chain_state st; + st.bind_root(t.handle()); + st.arm_root(); t.release(); + auto c = coro_chain::from_address(&st); { thread_pool pool(1); pool.make_service(pool.get_executor(), c); @@ -1186,8 +1210,11 @@ struct thread_pool_test int down = 0; auto probe = [](destroy_count_t) -> task { co_return; }; auto t = probe(destroy_count_t(down)); - continuation c{t.handle()}; + chain_state st; + st.bind_root(t.handle()); + st.arm_root(); t.release(); + auto c = coro_chain::from_address(&st); { thread_pool pool(1); pool.make_service(pool.get_executor(), c); @@ -1203,13 +1230,16 @@ struct thread_pool_test constexpr int n = 16; int down = 0; auto probe = [](destroy_count_t) -> task { co_return; }; - std::vector cs; + std::array states; + std::vector cs; cs.reserve(n); for(int i = 0; i < n; ++i) { auto t = probe(destroy_count_t(down)); - cs.push_back(continuation{t.handle()}); + states[i].bind_root(t.handle()); + states[i].arm_root(); t.release(); + cs.push_back(coro_chain::from_address(&states[i])); } { thread_pool pool(1); diff --git a/test/unit/ex/work_guard.cpp b/test/unit/ex/work_guard.cpp index fe0ba778f..a1d3d7d62 100644 --- a/test/unit/ex/work_guard.cpp +++ b/test/unit/ex/work_guard.cpp @@ -64,13 +64,13 @@ struct guard_test_executor } std::coroutine_handle<> - dispatch(continuation& c) const + dispatch(coro_chain&& c) const { - return c.h; + return c.release_handle(); } void - post(continuation&) const + post(coro_chain&&) const { } }; diff --git a/test/unit/fault/thread_pool_faults.cpp b/test/unit/fault/thread_pool_faults.cpp index d902e5fff..9e5a35285 100644 --- a/test/unit/fault/thread_pool_faults.cpp +++ b/test/unit/fault/thread_pool_faults.cpp @@ -9,7 +9,7 @@ #include -#include +#include #include "fault.hpp" #include "test_suite.hpp" @@ -41,50 +41,60 @@ struct thread_pool_faults_test void testRetryStartsOnlyMissingThreads() { - // Declared first: join() can stop the pool with c2 still - // queued, and the destructor then abandons it. - continuation c1, c2; - c1.h = c2.h = std::noop_coroutine(); + chain_state s1, s2; + s1.bind_root(std::noop_coroutine()); + s1.arm_root(); + s2.bind_root(std::noop_coroutine()); + s2.arm_root(); + coro_chain c1 = coro_chain::from_address(&s1); + coro_chain c2 = coro_chain::from_address(&s2); thread_pool pool(2); { fault_scope fault(sys::pthread_create, EAGAIN, 2); BOOST_TEST_THROWS( - pool.get_executor().post(c1), std::system_error); + pool.get_executor().post(std::move(c1)), std::system_error); BOOST_TEST(fault.fired()); } { fault_scope counter(sys::pthread_create, EAGAIN, count_only); - pool.get_executor().post(c2); + pool.get_executor().post(std::move(c2)); BOOST_TEST_EQ(counter.count(), 1u); } pool.join(); + std::ignore = c1.release_handle(); + std::ignore = c2.release_handle(); } // The first worker fails to start, so the retry starts both. void testRetryAfterFirstThreadFails() { - // Declared first: join() can stop the pool with c2 still - // queued, and the destructor then abandons it. - continuation c1, c2; - c1.h = c2.h = std::noop_coroutine(); + chain_state s1, s2; + s1.bind_root(std::noop_coroutine()); + s1.arm_root(); + s2.bind_root(std::noop_coroutine()); + s2.arm_root(); + coro_chain c1 = coro_chain::from_address(&s1); + coro_chain c2 = coro_chain::from_address(&s2); thread_pool pool(2); { fault_scope fault(sys::pthread_create, EAGAIN); BOOST_TEST_THROWS( - pool.get_executor().post(c1), std::system_error); + pool.get_executor().post(std::move(c1)), std::system_error); BOOST_TEST(fault.fired()); } { fault_scope counter(sys::pthread_create, EAGAIN, count_only); - pool.get_executor().post(c2); + pool.get_executor().post(std::move(c2)); BOOST_TEST_EQ(counter.count(), 2u); } pool.join(); + std::ignore = c1.release_handle(); + std::ignore = c2.release_handle(); } void diff --git a/test/unit/io/any_read_stream.cpp b/test/unit/io/any_read_stream.cpp index 0aad1557e..e9d7d38ff 100644 --- a/test/unit/io/any_read_stream.cpp +++ b/test/unit/io/any_read_stream.cpp @@ -11,7 +11,6 @@ #include #include -#include #include #include #include @@ -699,7 +698,7 @@ class any_read_stream_test auto unused = s.read_some(mutable_buffer(&d, 1)); } BOOST_TEST_EQ(down, 0); - capy::abandon(slot); + slot.reset(); BOOST_TEST_EQ(down, 1); } @@ -723,7 +722,7 @@ class any_read_stream_test BOOST_TEST(static_cast(slot)); s.reset(); BOOST_TEST_EQ(down, 1); - capy::abandon(slot); + slot.reset(); BOOST_TEST_EQ(down, 1); } @@ -751,9 +750,9 @@ class any_read_stream_test BOOST_TEST_EQ(down, 1); run_async(ex)(op(s)); BOOST_TEST(static_cast(second)); - capy::abandon(first); + first.reset(); BOOST_TEST_EQ(down, 1); - capy::abandon(second); + second.reset(); BOOST_TEST_EQ(down, 2); } @@ -783,7 +782,7 @@ class any_read_stream_test BOOST_TEST_EQ(st.ops_down, 1); BOOST_TEST_EQ(st.late, 0); - capy::abandon(st.slot); + st.slot.reset(); BOOST_TEST_EQ(st.ops_down, 1); } diff --git a/test/unit/io/any_stream.cpp b/test/unit/io/any_stream.cpp index f64666f22..a9c7f3f24 100644 --- a/test/unit/io/any_stream.cpp +++ b/test/unit/io/any_stream.cpp @@ -13,7 +13,6 @@ #include #include #include -#include #include #include #include @@ -325,7 +324,7 @@ class any_stream_test BOOST_TEST_EQ(st.ops_down, 1); BOOST_TEST_EQ(st.late, 0); - capy::abandon(st.slot); + st.slot.reset(); BOOST_TEST_EQ(st.ops_down, 1); } diff --git a/test/unit/io/any_write_stream.cpp b/test/unit/io/any_write_stream.cpp index 323e33a3f..7b7400aa1 100644 --- a/test/unit/io/any_write_stream.cpp +++ b/test/unit/io/any_write_stream.cpp @@ -11,7 +11,6 @@ #include #include -#include #include #include #include @@ -597,7 +596,7 @@ class any_write_stream_test auto unused = s.write_some(make_buffer(&d, 1)); } BOOST_TEST_EQ(down, 0); - capy::abandon(slot); + slot.reset(); BOOST_TEST_EQ(down, 1); } @@ -621,7 +620,7 @@ class any_write_stream_test BOOST_TEST(static_cast(slot)); s.reset(); BOOST_TEST_EQ(down, 1); - capy::abandon(slot); + slot.reset(); BOOST_TEST_EQ(down, 1); } @@ -649,9 +648,9 @@ class any_write_stream_test BOOST_TEST_EQ(down, 1); run_async(ex)(op(s)); BOOST_TEST(static_cast(second)); - capy::abandon(first); + first.reset(); BOOST_TEST_EQ(down, 1); - capy::abandon(second); + second.reset(); BOOST_TEST_EQ(down, 2); } diff --git a/test/unit/io/write_now.cpp b/test/unit/io/write_now.cpp index 7a224243e..54997635a 100644 --- a/test/unit/io/write_now.cpp +++ b/test/unit/io/write_now.cpp @@ -12,7 +12,6 @@ #include #include -#include #include #include #include @@ -64,8 +63,9 @@ struct parking_stream std::coroutine_handle<> await_suspend(std::coroutine_handle<> h, await_context const* env) noexcept { - slot->h = h; - slot->owner = env->owner; + if(env->chain) + slot->chain_ = env->park(h); + slot->raw_h_ = h; return std::noop_coroutine(); } results await_resume() const noexcept @@ -396,7 +396,7 @@ class write_now_test run_async(ex, counting_allocator(st))( parent(destroy_count_t(parent_down))); BOOST_TEST(slot); - capy::abandon(slot); + slot.reset(); BOOST_TEST_EQ(parent_down, 1); BOOST_TEST(st.allocs > 1); BOOST_TEST(st.balanced()); @@ -452,7 +452,7 @@ class write_now_test BOOST_TEST_EQ(first, 1u); BOOST_TEST_EQ(parent_down, 0); BOOST_TEST(slot); - capy::abandon(slot); + slot.reset(); BOOST_TEST_EQ(parent_down, 1); } diff --git a/test/unit/task.cpp b/test/unit/task.cpp index e01705b6b..a70172fb7 100644 --- a/test/unit/task.cpp +++ b/test/unit/task.cpp @@ -11,7 +11,6 @@ // Test that header file is self-contained. #include -#include #include #include #include @@ -43,6 +42,8 @@ static_assert(ContextAwaitable>); static_assert(ContextAwaitable>); static_assert(ContextRunnable>); static_assert(ContextRunnable>); +static_assert(sizeof(task) == sizeof(void*)); +static_assert(sizeof(task) == sizeof(void*)); // Verify set_continuation/set_environment are part of ContextRunnable static_assert(requires(task::promise_type& p) { @@ -84,17 +85,17 @@ struct tracking_executor void on_work_started() const noexcept {} void on_work_finished() const noexcept {} - std::coroutine_handle<> dispatch(continuation& c) const + std::coroutine_handle<> dispatch(coro_chain&& c) const { ++(*dispatch_count_); if (dispatch_log) dispatch_log->push_back(id); - return c.h; + return c.release_handle(); } - void post(continuation& c) const + void post(coro_chain&& c) const { - c.h.resume(); + c.resume(); } }; @@ -1352,7 +1353,7 @@ struct task_test run_async(ex, counting_allocator(st))( parent(&slot, destroy_count_t(parent_down))); BOOST_TEST(slot); - capy::abandon(slot); + slot.reset(); BOOST_TEST_EQ(child_down, 1); BOOST_TEST_EQ(parent_down, 1); BOOST_TEST(st.allocs > 0); @@ -1366,7 +1367,7 @@ struct task_test lease_resource mr; int leaf_down = 0, mid_down = 0, owner_down = 0; parked slot; - std::queue q; + std::queue q; queuing_executor ex(q); auto leaf = [](parked* s, destroy_count_t) -> task @@ -1386,7 +1387,7 @@ struct task_test pump(q); BOOST_TEST(slot); - capy::abandon(slot); + slot.reset(); pump(q); BOOST_TEST_EQ(leaf_down, 1); BOOST_TEST_EQ(mid_down, 1); @@ -1403,7 +1404,7 @@ struct task_test lease_resource mr; int leaf_down = 0, root_down = 0; parked slot; - std::queue q; + std::queue q; queuing_executor ex(q); auto leaf = [](parked* s, destroy_count_t) -> task @@ -1421,7 +1422,7 @@ struct task_test pump(q); BOOST_TEST(slot); - capy::abandon(slot); + slot.reset(); pump(q); BOOST_TEST_EQ(leaf_down, 1); BOOST_TEST_EQ(root_down, 1); @@ -1476,7 +1477,7 @@ struct task_test note local(log, "root local"); co_await mid(note(log, "mid param")); }; - std::queue q; + std::queue q; queuing_executor ex(q); run_async(ex, [n = note(log, "handler")] { BOOST_TEST(false); }, @@ -1485,7 +1486,7 @@ struct task_test pump(q); BOOST_TEST(slot); - capy::abandon(slot); + slot.reset(); pump(q); } std::vector const expected{ @@ -1502,7 +1503,7 @@ struct task_test int down = 0; parked slot; { - std::queue q; + std::queue q; queuing_executor ex(q); run_async(ex, counting_allocator(st))( nest_chain(depth, &slot, &down, destroy_count_t(down))); @@ -1510,7 +1511,7 @@ struct task_test BOOST_TEST(slot); BOOST_TEST_EQ(down, 0); - capy::abandon(slot); + slot.reset(); pump(q); } BOOST_TEST_EQ(down, depth + 1); @@ -1545,7 +1546,7 @@ struct task_test run_async(ex, counting_allocator(st))( parent(&slot, destroy_count_t(parent_down))); BOOST_TEST(slot); - capy::abandon(slot); + slot.reset(); BOOST_TEST_EQ(sub_down, 1); BOOST_TEST_EQ(parent_down, 1); BOOST_TEST(st.allocs > 0); @@ -1557,7 +1558,7 @@ struct task_test void testDestroyAwaitedChildThroughRun() { int child_down = 0, parent_down = 0; - std::queue q; + std::queue q; { int dispatch_count = 0; test_executor ex(dispatch_count); @@ -1572,9 +1573,9 @@ struct task_test }; run_async(caller)(parent(destroy_count_t(parent_down))); BOOST_TEST_EQ(q.size(), 1u); - auto start = q.front(); + auto start = std::move(q.front()); q.pop(); - safe_resume(start.h); + start.resume(); BOOST_TEST_EQ(child_down, 1); BOOST_TEST_EQ(parent_down, 0); BOOST_TEST(!q.empty()); diff --git a/test/unit/test/stream.cpp b/test/unit/test/stream.cpp index 93aa6109d..9ed214f65 100644 --- a/test/unit/test/stream.cpp +++ b/test/unit/test/stream.cpp @@ -684,7 +684,7 @@ class stream_test // Driven manually on a queuing executor for deterministic, // non-blocking control (mirrors async_mutex's cancellation test). auto [a, b] = make_stream_pair(); - std::queue q; + std::queue q; queuing_executor ex(q); std::stop_source ss; @@ -703,9 +703,11 @@ class stream_test auto h = reader.handle(); reader.release(); + chain_state st; await_context env; env.executor = executor_ref(ex); env.stop_token = ss.get_token(); + env.chain = &st; h.promise().set_environment(&env); // No data available: the read suspends. @@ -716,8 +718,9 @@ class stream_test ss.request_stop(); BOOST_TEST(! q.empty()); - q.front().h.resume(); + auto c = std::move(q.front()); q.pop(); + c.resume(); BOOST_TEST(reader_done); BOOST_TEST(reader_ec == make_error_code(error::canceled)); @@ -755,7 +758,7 @@ class stream_test // coroutine, which another thread could then resume and finish // while await_suspend still writes to its frame. auto [a, b] = make_stream_pair(); - std::queue q; + std::queue q; queuing_executor ex(q); std::stop_source ss; ss.request_stop(); @@ -795,7 +798,7 @@ class stream_test // the stop callback and unlink the pending slot, so a later peer // operation does not touch a freed claim flag. auto [a, b] = make_stream_pair(); - std::queue q; + std::queue q; queuing_executor ex(q); std::stop_source ss; @@ -809,9 +812,11 @@ class stream_test auto h = reader.handle(); reader.release(); + chain_state st; await_context env; env.executor = executor_ref(ex); env.stop_token = ss.get_token(); + env.chain = &st; h.promise().set_environment(&env); h.resume(); diff --git a/test/unit/test_helpers.hpp b/test/unit/test_helpers.hpp index 6a0323244..d72878987 100644 --- a/test/unit/test_helpers.hpp +++ b/test/unit/test_helpers.hpp @@ -692,7 +692,8 @@ struct park_awaitable std::coroutine_handle<> await_suspend(std::coroutine_handle<> h, await_context const* env) noexcept { - slot->chain_ = env->park(h); + if(env->chain) + slot->chain_ = env->park(h); slot->raw_h_ = h; return std::noop_coroutine(); } @@ -842,6 +843,27 @@ struct lease } }; +/** Helper to wrap an unstarted coroutine handle into a 1-frame `coro_chain`. + + Used by low-level executor unit tests that post a raw coroutine handle + without `run_async`. +*/ +struct root_chain_holder +{ + chain_state state_; + + root_chain_holder() = default; + root_chain_holder(root_chain_holder const&) = delete; + root_chain_holder& operator=(root_chain_holder const&) = delete; + + coro_chain bind(std::coroutine_handle<> h) noexcept + { + state_.bind_root(h); + state_.arm_root(); + return coro_chain::from_address(&state_); + } +}; + /// Resume queued continuations in FIFO order until the queue is empty. inline void pump(std::queue& q) diff --git a/test/unit/when_all.cpp b/test/unit/when_all.cpp index ac3967bad..a57126fcd 100644 --- a/test/unit/when_all.cpp +++ b/test/unit/when_all.cpp @@ -13,7 +13,6 @@ #include #include #include -#include #include #include #include @@ -1348,7 +1347,7 @@ struct when_all_results_test void testRunnersDestroyedBeforeStartDestroyParent() { int a_down = 0, b_down = 0, parent_down = 0; - std::queue q; + std::queue q; auto branch = [](destroy_count_t) -> task> { co_return results<>{}; @@ -1361,20 +1360,20 @@ struct when_all_results_test }; run_async(queuing_executor(q))(parent(destroy_count_t(parent_down))); BOOST_TEST_EQ(q.size(), 1u); - auto start = q.front(); + auto start = std::move(q.front()); q.pop(); - safe_resume(start.h); // parent posts both runners + start.resume(); // parent posts both runners BOOST_TEST_EQ(q.size(), 2u); // An unstarted runner owns no branch: the branches stay with the // join until it is unwound. - capy::abandon(q.front()); + q.front().reset(); q.pop(); BOOST_TEST_EQ(a_down, 0); BOOST_TEST_EQ(b_down, 0); BOOST_TEST_EQ(parent_down, 0); - capy::abandon(q.front()); + q.front().reset(); q.pop(); pump(q); BOOST_TEST_EQ(a_down, 1); @@ -1404,10 +1403,10 @@ struct when_all_results_test test_executor ex(n); run_async(ex)(parent(destroy_count_t(parent_down))); BOOST_TEST(sa && sb); - capy::abandon(sa); + sa.reset(); BOOST_TEST_EQ(a_down, 1); BOOST_TEST_EQ(parent_down, 0); // b still holds a share - capy::abandon(sb); + sb.reset(); BOOST_TEST_EQ(b_down, 1); BOOST_TEST_EQ(parent_down, 1); } @@ -1432,7 +1431,7 @@ struct when_all_results_test int n = 0; test_executor ex(n); run_async(ex)(parent(destroy_count_t(parent_down))); - capy::abandon(sa); + sa.reset(); sb.resume(); BOOST_TEST(!resumed); BOOST_TEST_EQ(parent_down, 1); @@ -1462,8 +1461,8 @@ struct when_all_results_test test_executor ex(n); run_async(ex, counting_allocator(st))( parent(&sa, &sb, destroy_count_t(parent_down))); - capy::abandon(sa); - capy::abandon(sb); + sa.reset(); + sb.reset(); BOOST_TEST_EQ(parent_down, 1); BOOST_TEST(st.allocs > 0); BOOST_TEST(st.balanced()); @@ -1496,8 +1495,8 @@ struct when_all_results_test }; run_async(ex)(owner(destroy_count_t(owner_down))); BOOST_TEST(sa && sb); - capy::abandon(sa); - capy::abandon(sb); + sa.reset(); + sb.reset(); BOOST_TEST_EQ(a_down, 1); BOOST_TEST_EQ(b_down, 1); BOOST_TEST_EQ(owner_down, 1); @@ -1532,7 +1531,7 @@ struct when_all_results_test for(int i = 0; i < count; ++i) { BOOST_TEST(slots[i]); - capy::abandon(slots[i]); + slots[i].reset(); for(int j = 0; j < count; ++j) BOOST_TEST_EQ(down[j], j <= i ? 1 : 0); BOOST_TEST_EQ(parent_down, i == count - 1 ? 1 : 0); @@ -1561,7 +1560,7 @@ struct when_all_results_test run_async(ex)(parent(destroy_count_t(parent_down))); sa.resume(); BOOST_TEST_EQ(parent_down, 0); - capy::abandon(sb); + sb.reset(); BOOST_TEST(!resumed); BOOST_TEST_EQ(parent_down, 1); } @@ -1594,12 +1593,12 @@ struct when_all_results_test test_executor ex(n); run_async(ex)(parent(destroy_count_t(parent_down))); BOOST_TEST(sa && sb && sc); - capy::abandon(sb); - capy::abandon(sa); + sb.reset(); + sa.reset(); BOOST_TEST_EQ(leaf_down, 2); BOOST_TEST_EQ(inner_down, 0); BOOST_TEST_EQ(parent_down, 0); - capy::abandon(sc); + sc.reset(); BOOST_TEST_EQ(leaf_down, 3); BOOST_TEST_EQ(inner_down, 1); BOOST_TEST_EQ(parent_down, 1); @@ -1611,7 +1610,7 @@ struct when_all_results_test // sanitizer, and only libstdc++'s callback order makes it reachable. void testStopLosingLastBranch() { - std::queue q; + std::queue q; bool closed = false; int parent_down = 0; async_event ev; @@ -1644,7 +1643,7 @@ struct when_all_results_test { int leaf_down = 0, hop_down = 0, parent_down = 0, n = 0; parked sa, sb; - std::queue q; + std::queue q; queuing_executor caller(q); test_executor inner(n); auto leaf = [](parked* s, destroy_count_t) -> task @@ -1666,7 +1665,7 @@ struct when_all_results_test pump(q); BOOST_TEST(sa && sb); - capy::abandon(sa); + sa.reset(); BOOST_TEST_EQ(leaf_down, 1); BOOST_TEST_EQ(hop_down, 0); // lost on the caller's executor BOOST_TEST(!q.empty()); @@ -1674,7 +1673,7 @@ struct when_all_results_test BOOST_TEST_EQ(hop_down, 1); BOOST_TEST_EQ(parent_down, 0); - capy::abandon(sb); + sb.reset(); pump(q); BOOST_TEST_EQ(leaf_down, 2); BOOST_TEST_EQ(hop_down, 2); @@ -1688,7 +1687,7 @@ struct when_all_results_test for(bool range : {false, true}) { lease_resource mr; - std::queue q; + std::queue q; bool closed = false; int owner_down = 0; auto branch = []() -> task> @@ -1720,9 +1719,9 @@ struct when_all_results_test closed = true; while(!q.empty()) { - auto c = q.front(); + auto c = std::move(q.front()); q.pop(); - capy::abandon(c); + c.reset(); } BOOST_TEST_EQ(owner_down, 1); BOOST_TEST(mr.balanced()); @@ -1751,9 +1750,9 @@ struct when_all_results_test test_executor ex(n); run_async(ex)(parent()); BOOST_TEST(!seen.stop_requested()); - capy::abandon(sa); + sa.reset(); BOOST_TEST(seen.stop_requested()); - capy::abandon(sb); + sb.reset(); } void diff --git a/test/unit/when_any.cpp b/test/unit/when_any.cpp index 049a1e5de..a7b9a3abf 100644 --- a/test/unit/when_any.cpp +++ b/test/unit/when_any.cpp @@ -14,7 +14,6 @@ #include #include #include -#include #include #include #include @@ -540,7 +539,7 @@ struct when_any_vector_test void testLongLivedTasksCancelled() { - std::queue work_queue; + std::queue work_queue; queuing_executor ex(work_queue); std::atomic cancelled_count{0}; @@ -1124,7 +1123,7 @@ struct when_any_results_test void testRunnersDestroyedBeforeStartDestroyParent() { int a_down = 0, b_down = 0, parent_down = 0; - std::queue q; + std::queue q; auto branch = [](destroy_count_t) -> task> { co_return results<>{}; @@ -1137,24 +1136,24 @@ struct when_any_results_test }; run_async(queuing_executor(q))(parent(destroy_count_t(parent_down))); BOOST_TEST_EQ(q.size(), 1u); - auto start = q.front(); + auto start = std::move(q.front()); q.pop(); - safe_resume(start.h); // parent posts both runners + start.resume(); // parent posts both runners BOOST_TEST_EQ(q.size(), 2u); - auto ra = q.front(); + auto ra = std::move(q.front()); q.pop(); - auto rb = q.front(); + auto rb = std::move(q.front()); q.pop(); // An unstarted runner owns no branch: the branches stay with the // join until it is unwound. - capy::abandon(ra); + ra.reset(); pump(q); BOOST_TEST_EQ(a_down, 0); BOOST_TEST_EQ(b_down, 0); BOOST_TEST_EQ(parent_down, 0); - capy::abandon(rb); + rb.reset(); pump(q); BOOST_TEST_EQ(a_down, 1); BOOST_TEST_EQ(b_down, 1); @@ -1188,8 +1187,8 @@ struct when_any_results_test }; run_async(ex)(owner(destroy_count_t(owner_down))); BOOST_TEST(sa && sb); - capy::abandon(sa); - capy::abandon(sb); + sa.reset(); + sb.reset(); BOOST_TEST_EQ(a_down, 1); BOOST_TEST_EQ(b_down, 1); BOOST_TEST_EQ(owner_down, 1); @@ -1224,7 +1223,7 @@ struct when_any_results_test for(int i = 0; i < count; ++i) { BOOST_TEST(slots[i]); - capy::abandon(slots[i]); + slots[i].reset(); for(int j = 0; j < count; ++j) BOOST_TEST_EQ(down[j], j <= i ? 1 : 0); BOOST_TEST_EQ(parent_down, i == count - 1 ? 1 : 0); @@ -1254,7 +1253,7 @@ struct when_any_results_test sa.resume(); BOOST_TEST(!resumed); BOOST_TEST_EQ(parent_down, 0); - capy::abandon(sb); + sb.reset(); BOOST_TEST(!resumed); BOOST_TEST_EQ(parent_down, 1); } @@ -1281,10 +1280,10 @@ struct when_any_results_test test_executor ex(n); run_async(ex)(parent(destroy_count_t(parent_down))); BOOST_TEST(sa && sb); - capy::abandon(sa); + sa.reset(); BOOST_TEST_EQ(a_down, 1); BOOST_TEST_EQ(parent_down, 0); // b still holds a share - capy::abandon(sb); + sb.reset(); BOOST_TEST_EQ(b_down, 1); BOOST_TEST_EQ(parent_down, 1); } @@ -1314,7 +1313,7 @@ struct when_any_results_test int n = 0; test_executor ex(n); run_async(ex)(parent(destroy_count_t(parent_down))); - capy::abandon(sa); + sa.reset(); sb.resume(); BOOST_TEST(!resumed); BOOST_TEST_EQ(parent_down, 1); @@ -1340,7 +1339,7 @@ struct when_any_results_test int n = 0; test_executor ex(n); run_async(ex)(parent(destroy_count_t(parent_down))); - capy::abandon(sa); + sa.reset(); BOOST_TEST_EQ(parent_down, 0); sb.resume(); BOOST_TEST(!resumed); @@ -1371,8 +1370,8 @@ struct when_any_results_test test_executor ex(n); run_async(ex, counting_allocator(st))( parent(&sa, &sb, destroy_count_t(parent_down))); - capy::abandon(sa); - capy::abandon(sb); + sa.reset(); + sb.reset(); BOOST_TEST_EQ(parent_down, 1); BOOST_TEST(st.allocs > 0); BOOST_TEST(st.balanced()); @@ -1384,7 +1383,7 @@ struct when_any_results_test // sanitizer, and only libstdc++'s callback order makes it reachable. void testStopLosingLastBranch() { - std::queue q; + std::queue q; bool closed = false; int parent_down = 0; async_event ev; @@ -1418,7 +1417,7 @@ struct when_any_results_test for(bool range : {false, true}) { lease_resource mr; - std::queue q; + std::queue q; bool closed = false; int owner_down = 0; auto branch = []() -> task> @@ -1450,9 +1449,9 @@ struct when_any_results_test closed = true; while(!q.empty()) { - auto c = q.front(); + auto c = std::move(q.front()); q.pop(); - capy::abandon(c); + c.reset(); } BOOST_TEST_EQ(owner_down, 1); BOOST_TEST(mr.balanced()); @@ -1481,9 +1480,9 @@ struct when_any_results_test test_executor ex(n); run_async(ex)(parent()); BOOST_TEST(!seen.stop_requested()); - capy::abandon(sa); + sa.reset(); BOOST_TEST(seen.stop_requested()); - capy::abandon(sb); + sb.reset(); } void From 002364b87296e38d2e2807cb1ee98d44f5af844a Mon Sep 17 00:00:00 2001 From: Vinnie Falco Date: Sat, 5 Dec 2026 10:12:04 -0800 Subject: [PATCH 5/6] Update examples and benchmarks for coro_chain Migrate all example/ and bench/ targets (including custom_executor, gui_integration, early-quitter, asio, awaitable-sender, sender-bridge, and cuda) to coro_chain, root_promise_base, and root_work_base, and retire example/asio/api/abandon_guard.hpp. --- bench/beman/awaitable_sender.hpp | 40 +++------ bench/beman/ctxaw_read_stream.hpp | 7 +- bench/beman/sender_await_context.hpp | 12 +-- bench/bench.cpp | 8 +- bench/stdexec/awaitable_sender.hpp | 40 +++------ bench/stdexec/ctxaw_read_stream.hpp | 7 +- bench/stdexec/sender_await_context.hpp | 13 +-- example/asio/api/abandon_guard.hpp | 86 ------------------- example/asio/api/capy_streams.cpp | 37 ++------ example/asio/api/uni_stream.hpp | 21 ++--- example/asio/api/use_capy.hpp | 21 ++--- .../awaitable_sender_detail.hpp | 83 +++++------------- example/awaitable-sender/read_op.hpp | 16 +--- example/awaitable-sender/tests.cpp | 81 ++++++----------- .../cuda/datamovement/cuda_datamovement.hpp | 32 +++---- .../notification_strategies.hpp | 34 ++++---- example/custom-executor/custom_executor.cpp | 38 +++----- example/early-quitter/checks.cpp | 49 +++++------ example/early-quitter/quitter.hpp | 19 ++-- example/gui-integration/gui_integration.cpp | 42 ++++----- example/sender-bridge/sender_awaitable.hpp | 14 +-- 21 files changed, 214 insertions(+), 486 deletions(-) delete mode 100644 example/asio/api/abandon_guard.hpp diff --git a/bench/beman/awaitable_sender.hpp b/bench/beman/awaitable_sender.hpp index 4b3d941e1..c178d8fbc 100644 --- a/bench/beman/awaitable_sender.hpp +++ b/bench/beman/awaitable_sender.hpp @@ -14,6 +14,7 @@ #include #include #include +#include #include #include @@ -100,13 +101,6 @@ template constexpr bool is_compound_ec_result_v = is_compound_ec_result::value; -struct frame_cb -{ - void (*resume)(frame_cb*); - void (*destroy)(frame_cb*); - void* data; -}; - } // namespace detail /** Sender that wraps a ContextAwaitable. @@ -163,6 +157,7 @@ struct awaitable_sender template struct op_state + : root_work_base> { using operation_state_concept = beman::execution::operation_state_t; @@ -176,14 +171,11 @@ struct awaitable_sender CtxAw aw_; Receiver rcvr_; executor_type ex_; - await_context env_; - detail::frame_cb cb_; op_state(CtxAw aw, Receiver rcvr) : aw_(std::move(aw)) , rcvr_(std::move(rcvr)) , ex_{} - , cb_{} { } @@ -192,15 +184,12 @@ struct awaitable_sender op_state& operator=(op_state const&) = delete; op_state& operator=(op_state&&) = delete; - static void - on_resume(detail::frame_cb* p) noexcept + void on_resume() noexcept { - auto* self = static_cast(p->data); - self->complete(); + complete(); } - static void - on_destroy(detail::frame_cb*) noexcept + void on_abandon() noexcept { } @@ -211,7 +200,7 @@ struct awaitable_sender if constexpr (std::is_void_v) { aw_.await_resume(); - if(env_.stop_token.stop_requested()) + if(this->env_.stop_token.stop_requested()) beman::execution::set_stopped( std::move(rcvr_)); else @@ -222,7 +211,7 @@ struct awaitable_sender detail::is_compound_ec_result_v) { auto result = aw_.await_resume(); - if(env_.stop_token.stop_requested()) + if(this->env_.stop_token.stop_requested()) { beman::execution::set_stopped( std::move(rcvr_)); @@ -243,7 +232,7 @@ struct awaitable_sender detail::is_ec_outcome_v) { auto result = aw_.await_resume(); - if(env_.stop_token.stop_requested()) + if(this->env_.stop_token.stop_requested()) { beman::execution::set_stopped( std::move(rcvr_)); @@ -267,7 +256,7 @@ struct awaitable_sender else { auto result = aw_.await_resume(); - if(env_.stop_token.stop_requested()) + if(this->env_.stop_token.stop_requested()) beman::execution::set_stopped( std::move(rcvr_)); else @@ -299,7 +288,7 @@ struct awaitable_sender beman::execution::get_stop_token_t{}); } - env_ = await_context{ex_, st, nullptr}; + auto h = this->bind_chain(ex_, st); if(aw_.await_ready()) { @@ -307,15 +296,8 @@ struct awaitable_sender return; } - cb_.resume = &on_resume; - cb_.destroy = &on_destroy; - cb_.data = this; - - auto h = std::coroutine_handle<>::from_address( - static_cast(&cb_)); - auto resumed = detail::call_await_suspend( - &aw_, h, &env_); + &aw_, h, &this->env_); if(resumed == h) complete(); } diff --git a/bench/beman/ctxaw_read_stream.hpp b/bench/beman/ctxaw_read_stream.hpp index a79d97238..b0cfc6747 100644 --- a/bench/beman/ctxaw_read_stream.hpp +++ b/bench/beman/ctxaw_read_stream.hpp @@ -12,7 +12,7 @@ #include #include -#include +#include #include #include #include @@ -27,8 +27,6 @@ struct ctxaw_read_stream { struct read_awaitable { - boost::capy::continuation cont_{}; - bool await_ready() const noexcept { return false; } std::coroutine_handle<> @@ -36,8 +34,7 @@ struct ctxaw_read_stream std::coroutine_handle<> h, boost::capy::await_context const* env) { - cont_.h = h; - env->executor.post(cont_); + env->executor.post(env->park(h)); return std::noop_coroutine(); } diff --git a/bench/beman/sender_await_context.hpp b/bench/beman/sender_await_context.hpp index 20bc9920c..b37c1e742 100644 --- a/bench/beman/sender_await_context.hpp +++ b/bench/beman/sender_await_context.hpp @@ -21,7 +21,7 @@ #include "sender_thread_pool.hpp" #include "awaitable_sender.hpp" -#include +#include #include #include @@ -53,16 +53,16 @@ struct sender_as_capy_executor pool_->on_work_finished(); } - void post(boost::capy::continuation& c) const; + void post(boost::capy::coro_chain&& c) const; // Return the handle for symmetric transfer so the // caller resumes the coroutine inline. Posting would // cause a lifetime issue since run_async expects to // hand off ownership via symmetric transfer. std::coroutine_handle<> - dispatch(boost::capy::continuation& c) const + dispatch(boost::capy::coro_chain&& c) const { - return c.h; + return c.release_handle(); } bool operator==( @@ -201,10 +201,10 @@ struct scheduled_resume }; inline void sender_as_capy_executor::post( - boost::capy::continuation& c) const + boost::capy::coro_chain&& c) const { auto* p = new scheduled_resume( - pool_scheduler{pool_}, c.h); + pool_scheduler{pool_}, c.release_handle()); ex::start(p->op_); } diff --git a/bench/bench.cpp b/bench/bench.cpp index afd8bc2e7..da2d07050 100644 --- a/bench/bench.cpp +++ b/bench/bench.cpp @@ -81,14 +81,14 @@ class bench_io_context::executor_type { } - std::coroutine_handle<> dispatch(continuation& c) const + std::coroutine_handle<> dispatch(coro_chain&& c) const { - return c.h; + return c.release_handle(); } - void post(continuation& c) const + void post(coro_chain&& c) const { - c.h.resume(); + c.resume(); } void defer(std::coroutine_handle<> h) const diff --git a/bench/stdexec/awaitable_sender.hpp b/bench/stdexec/awaitable_sender.hpp index 61b1ae1cd..86e2bc1d8 100644 --- a/bench/stdexec/awaitable_sender.hpp +++ b/bench/stdexec/awaitable_sender.hpp @@ -14,6 +14,7 @@ #include #include #include +#include #include #include @@ -99,13 +100,6 @@ template constexpr bool is_compound_ec_result_v = is_compound_ec_result::value; -struct frame_cb -{ - void (*resume)(frame_cb*); - void (*destroy)(frame_cb*); - void* data; -}; - // Return the concrete executor by value, trying get_io_executor // on the env first, then falling back to the start scheduler. template @@ -174,6 +168,7 @@ struct awaitable_sender template struct op_state + : root_work_base> { using operation_state_concept = stdexec::operation_state_tag; @@ -190,14 +185,11 @@ struct awaitable_sender CtxAw aw_; Receiver rcvr_; executor_type ex_; - await_context env_; - detail::frame_cb cb_; op_state(CtxAw aw, Receiver rcvr) : aw_(std::move(aw)) , rcvr_(std::move(rcvr)) , ex_{} - , cb_{} { } @@ -206,15 +198,12 @@ struct awaitable_sender op_state& operator=(op_state const&) = delete; op_state& operator=(op_state&&) = delete; - static void - on_resume(detail::frame_cb* p) noexcept + void on_resume() noexcept { - auto* self = static_cast(p->data); - self->complete(); + complete(); } - static void - on_destroy(detail::frame_cb*) noexcept + void on_abandon() noexcept { } @@ -225,7 +214,7 @@ struct awaitable_sender if constexpr (std::is_void_v) { aw_.await_resume(); - if(env_.stop_token.stop_requested()) + if(this->env_.stop_token.stop_requested()) stdexec::set_stopped( std::move(rcvr_)); else @@ -236,7 +225,7 @@ struct awaitable_sender detail::is_compound_ec_result_v) { auto result = aw_.await_resume(); - if(env_.stop_token.stop_requested()) + if(this->env_.stop_token.stop_requested()) { stdexec::set_stopped( std::move(rcvr_)); @@ -257,7 +246,7 @@ struct awaitable_sender detail::is_ec_outcome_v) { auto result = aw_.await_resume(); - if(env_.stop_token.stop_requested()) + if(this->env_.stop_token.stop_requested()) { stdexec::set_stopped( std::move(rcvr_)); @@ -281,7 +270,7 @@ struct awaitable_sender else { auto result = aw_.await_resume(); - if(env_.stop_token.stop_requested()) + if(this->env_.stop_token.stop_requested()) stdexec::set_stopped( std::move(rcvr_)); else @@ -312,7 +301,7 @@ struct awaitable_sender stdexec::get_stop_token_t{}); } - env_ = await_context{ex_, st, nullptr}; + auto h = this->bind_chain(ex_, st); if(aw_.await_ready()) { @@ -320,15 +309,8 @@ struct awaitable_sender return; } - cb_.resume = &on_resume; - cb_.destroy = &on_destroy; - cb_.data = this; - - auto h = std::coroutine_handle<>::from_address( - static_cast(&cb_)); - auto resumed = detail::call_await_suspend( - &aw_, h, &env_); + &aw_, h, &this->env_); if(resumed == h) complete(); } diff --git a/bench/stdexec/ctxaw_read_stream.hpp b/bench/stdexec/ctxaw_read_stream.hpp index d62f010bb..b9484d4fd 100644 --- a/bench/stdexec/ctxaw_read_stream.hpp +++ b/bench/stdexec/ctxaw_read_stream.hpp @@ -12,7 +12,7 @@ #include #include -#include +#include #include #include #include @@ -27,8 +27,6 @@ struct ctxaw_read_stream { struct read_awaitable { - boost::capy::continuation cont_{}; - bool await_ready() const noexcept { return false; } std::coroutine_handle<> @@ -36,8 +34,7 @@ struct ctxaw_read_stream std::coroutine_handle<> h, boost::capy::await_context const* env) { - cont_.h = h; - env->executor.post(cont_); + env->executor.post(env->park(h)); return std::noop_coroutine(); } diff --git a/bench/stdexec/sender_await_context.hpp b/bench/stdexec/sender_await_context.hpp index 0aded0edb..ff0d61fbf 100644 --- a/bench/stdexec/sender_await_context.hpp +++ b/bench/stdexec/sender_await_context.hpp @@ -19,7 +19,7 @@ #include "awaitable_sender.hpp" -#include +#include #include #include @@ -65,14 +65,14 @@ struct sender_as_capy_executor void on_work_started() const noexcept {} void on_work_finished() const noexcept {} - void post(boost::capy::continuation& cont) const; + void post(boost::capy::coro_chain&& cont) const; // Return the handle for symmetric transfer so the // caller resumes the coroutine inline. std::coroutine_handle<> - dispatch(boost::capy::continuation& c) const + dispatch(boost::capy::coro_chain&& c) const { - return c.h; + return c.release_handle(); } bool operator==( @@ -82,14 +82,15 @@ struct sender_as_capy_executor // Heap-allocated trampoline; not zero-alloc by design. // Honest reflection of what exec::static_thread_pool costs. inline void sender_as_capy_executor::post( - boost::capy::continuation& cont) const + boost::capy::coro_chain&& cont) const { // upon_error eats the set_error_t(exception_ptr) channel // that stdexec::then advertises so start_detached's // no-error precondition is satisfied at the type level. + auto h = cont.release_handle(); exec::start_detached( stdexec::schedule(pool_->get_scheduler()) - | stdexec::then([&cont]() noexcept { cont.h.resume(); }) + | stdexec::then([h]() noexcept { h.resume(); }) | stdexec::upon_error([](auto&&) noexcept {})); } diff --git a/example/asio/api/abandon_guard.hpp b/example/asio/api/abandon_guard.hpp deleted file mode 100644 index 4b13d5a5b..000000000 --- a/example/asio/api/abandon_guard.hpp +++ /dev/null @@ -1,86 +0,0 @@ -// -// Copyright (c) 2026 Steve Gerbino -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// Official repository: https://github.com/cppalliance/capy -// - -#ifndef CAPY_EXAMPLE_ABANDON_GUARD_HPP -#define CAPY_EXAMPLE_ABANDON_GUARD_HPP - -#include -#include -#include - -#include - -// Rides in an Asio handler holding a parked coroutine. A handler -// destroyed without running, as when its io_context is destroyed, -// gives the coroutine up instead of leaking its chain. -class abandon_guard -{ - boost::capy::continuation* c_; - -public: - ~abandon_guard() - { - if(c_) - boost::capy::abandon(*c_); - } - - explicit abandon_guard(boost::capy::continuation& c) noexcept - : c_(&c) - { - } - - abandon_guard(abandon_guard&& other) noexcept - : c_(std::exchange(other.c_, nullptr)) - { - } - - abandon_guard(abandon_guard const&) = delete; - abandon_guard& operator=(abandon_guard const&) = delete; - abandon_guard& operator=(abandon_guard&&) = delete; - - // Return the held continuation, still given up on destruction. - boost::capy::continuation* get() const noexcept - { - return c_; - } - - // Return the continuation, which is no longer given up, or null - // if this guard holds none. - boost::capy::continuation* release() noexcept - { - return std::exchange(c_, nullptr); - } -}; - -// Resumes its coroutine when Asio runs it; gives it up when Asio -// destroys it unrun. -class resume_or_abandon -{ - abandon_guard g_; - -public: - explicit resume_or_abandon(boost::capy::continuation& c) noexcept - : g_(c) - { - } - - // Leave the coroutine to the caller, as when the post that was to - // carry it throws. Returns false if this handler was moved from. - bool release() noexcept - { - return g_.release() != nullptr; - } - - void operator()() - { - boost::capy::safe_resume(g_.release()->h); - } -}; - -#endif diff --git a/example/asio/api/capy_streams.cpp b/example/asio/api/capy_streams.cpp index 94499a5a4..c0e3e273b 100644 --- a/example/asio/api/capy_streams.cpp +++ b/example/asio/api/capy_streams.cpp @@ -8,7 +8,6 @@ // #include "capy_streams.hpp" -#include "abandon_guard.hpp" #include #include @@ -20,6 +19,7 @@ #include #include #include +#include #include #include #include @@ -83,7 +83,6 @@ class asio_socket MB buffers_; capy::results result_; std::shared_ptr cancel_; - capy::continuation cont_; public: read_awaitable( @@ -104,8 +103,6 @@ class asio_socket std::coroutine_handle<> h, capy::await_context const* env) { - cont_.h = h; - cont_.owner = env->owner; cancel_ = std::make_shared(env->stop_token); try @@ -114,14 +111,13 @@ class asio_socket capy::to_asio(buffers_), net::bind_cancellation_slot( cancel_->signal.slot(), - [this, ex = env->executor, g = abandon_guard(cont_)]( + [this, ex = env->executor, c = env->park(h)]( boost::system::error_code ec, std::size_t n) mutable { std::get<0>(result_) = ec; std::get<1>(result_) = n; - ex.post(*g.get()); - g.release(); + ex.post(std::move(c)); })); } catch(...) @@ -156,7 +152,6 @@ class asio_socket CB buffers_; capy::results result_; std::shared_ptr cancel_; - capy::continuation cont_; public: write_awaitable( @@ -177,8 +172,6 @@ class asio_socket std::coroutine_handle<> h, capy::await_context const* env) { - cont_.h = h; - cont_.owner = env->owner; cancel_ = std::make_shared(env->stop_token); try @@ -187,14 +180,13 @@ class asio_socket capy::to_asio(buffers_), net::bind_cancellation_slot( cancel_->signal.slot(), - [this, ex = env->executor, g = abandon_guard(cont_)]( + [this, ex = env->executor, c = env->park(h)]( boost::system::error_code ec, std::size_t n) mutable { std::get<0>(result_) = ec; std::get<1>(result_) = n; - ex.post(*g.get()); - g.release(); + ex.post(std::move(c)); })); } catch(...) @@ -257,26 +249,15 @@ class asio_executor void on_work_started() const noexcept {} void on_work_finished() const noexcept {} - std::coroutine_handle<> dispatch(capy::continuation& c) const + std::coroutine_handle<> dispatch(capy::coro_chain&& c) const { - post(c); + post(std::move(c)); return std::noop_coroutine(); } - void post(capy::continuation& c) const + void post(capy::coro_chain&& c) const { - resume_or_abandon r(c); - try - { - net::post(ioc_->get_executor(), std::move(r)); - } - catch(...) - { - // A handler Asio took and then destroyed has given `c` up, - // so the post must not also report it as still held. - if(r.release()) - throw; - } + net::post(ioc_->get_executor(), std::move(c)); } }; diff --git a/example/asio/api/uni_stream.hpp b/example/asio/api/uni_stream.hpp index 2c11cd941..16870fc4c 100644 --- a/example/asio/api/uni_stream.hpp +++ b/example/asio/api/uni_stream.hpp @@ -16,10 +16,10 @@ #include #include -#include "abandon_guard.hpp" #include "capy_streams.hpp" #include +#include #include #include #include @@ -57,26 +57,15 @@ class asio_executor_wrapper void on_work_started() const noexcept {} void on_work_finished() const noexcept {} - std::coroutine_handle<> dispatch(capy::continuation& c) const + std::coroutine_handle<> dispatch(capy::coro_chain&& c) const { - post(c); + post(std::move(c)); return std::noop_coroutine(); } - void post(capy::continuation& c) const + void post(capy::coro_chain&& c) const { - resume_or_abandon r(c); - try - { - net::post(ex_, std::move(r)); - } - catch(...) - { - // A handler Asio took and then destroyed has given `c` up, - // so the post must not also report it as still held. - if(r.release()) - throw; - } + net::post(ex_, std::move(c)); } }; diff --git a/example/asio/api/use_capy.hpp b/example/asio/api/use_capy.hpp index c1a8d824a..3a38d89fb 100644 --- a/example/asio/api/use_capy.hpp +++ b/example/asio/api/use_capy.hpp @@ -15,10 +15,8 @@ #include #include -#include "abandon_guard.hpp" - #include -#include +#include #include #include #include @@ -113,7 +111,6 @@ class capy_awaitable DeferredOp op_; result_type result_; std::shared_ptr cancel_; - capy::continuation cont_; public: explicit capy_awaitable(DeferredOp op) @@ -135,19 +132,15 @@ class capy_awaitable // Resume the caller on its executor when the Asio operation // completes. The completion handler may run on any thread, so we - // post the continuation through the executor rather than resuming - // inline; this restores the same-executor invariant. cont_ is a - // member, giving the continuation a stable address until the - // executor dequeues and resumes it. The guard gives the - // coroutine up if Asio destroys the handler without running it. - cont_.h = h; - cont_.owner = env->owner; - auto handler = [this, ex = env->executor, g = abandon_guard(cont_)]( + // post the coro_chain through the executor rather than resuming + // inline; this restores the same-executor invariant. If Asio + // destroys the handler without running it, ~coro_chain() unwinds + // the coroutine chain automatically. + auto handler = [this, ex = env->executor, c = env->park(h)]( Args... args) mutable { store_result(std::move(args)...); - ex.post(*g.get()); - g.release(); + ex.post(std::move(c)); }; try diff --git a/example/awaitable-sender/awaitable_sender_detail.hpp b/example/awaitable-sender/awaitable_sender_detail.hpp index 2518cf4eb..b9f36c111 100644 --- a/example/awaitable-sender/awaitable_sender_detail.hpp +++ b/example/awaitable-sender/awaitable_sender_detail.hpp @@ -11,11 +11,12 @@ #define BOOST_CAPY_EXAMPLE_AWAITABLE_SENDER_DETAIL_HPP #include +#include #include -#include #include #include #include +#include #include #include @@ -130,22 +131,6 @@ template constexpr bool is_compound_ec_result_v = is_compound_ec_result::value; -// ------------------------------------------------------- -// frame_cb: synthetic coroutine frame for callback handles -// -// The first two members match the coroutine frame layout -// used by MSVC, GCC, and Clang. from_address produces a -// coroutine_handle whose .resume() and .destroy() call our -// function pointers. -// ------------------------------------------------------- - -struct frame_cb -{ - void (*resume)(frame_cb*); - void (*destroy)(frame_cb*); - void* data; -}; - // declared only for decltype composition template auto concat_sigs( @@ -247,9 +232,9 @@ class scheduler_executor void set_value() && noexcept { - auto h = self_->c_.h; + auto c = std::move(self_->c_); delete self_; - h.resume(); + c.resume(); } // The scheduler refused the work (its context has @@ -268,9 +253,9 @@ class scheduler_executor void refuse() noexcept { - auto c = self_->c_; + auto c = std::move(self_->c_); delete self_; - capy::abandon(c); + c.reset(); } }; @@ -282,12 +267,11 @@ class scheduler_executor ex::schedule(std::declval()), std::declval())); - // A copy keeps the owner, which abandon needs. - continuation c_; + coro_chain c_; op_t op_; - holder(Sched s, continuation const& c) - : c_(c) + holder(Sched s, coro_chain&& c) + : c_(std::move(c)) , op_(ex::connect( ex::schedule(std::move(s)), resume_receiver{this})) @@ -318,24 +302,25 @@ class scheduler_executor return sched_ == other.sched_; } - void post(continuation& c) const + void post(coro_chain&& c) const { // the holder frees itself from the receiver on completion - auto* p = new holder(sched_, c); + auto* p = new holder(sched_, std::move(c)); ex::start(p->op_); } // A generic scheduler cannot answer "is the current thread // yours", so dispatch degrades to post. - std::coroutine_handle<> dispatch(continuation& c) const + std::coroutine_handle<> dispatch(coro_chain&& c) const { - post(c); + post(std::move(c)); return std::noop_coroutine(); } }; template struct awaitable_op_state + : root_work_base> { using operation_state_concept = ex::operation_state_t; using result_type = awaitable_result_t; @@ -401,10 +386,6 @@ struct awaitable_op_state // Reset to destroy the segment when it is abandoned. std::optional aw_; Receiver rcvr_; - await_context env_; - frame_cb cb_; - // The segment's owner, with cb_ as its coroutine. - chain_owner owner_; // stop_cb_ declared after stop_src_ so it is destroyed first: // on_stop holds a reference to stop_src_. std::stop_source stop_src_; @@ -430,7 +411,6 @@ struct awaitable_op_state awaitable_op_state(Aw aw, Receiver rcvr) : aw_(std::in_place, std::move(aw)) , rcvr_(std::move(rcvr)) - , cb_{} , stop_src_(make_stop_source()) { } @@ -440,26 +420,14 @@ struct awaitable_op_state awaitable_op_state& operator=(awaitable_op_state const&) = delete; awaitable_op_state& operator=(awaitable_op_state&&) = delete; - static void on_resume(frame_cb* p) noexcept + void on_resume() noexcept { - auto* self = static_cast(p->data); - if(self->owner_.abandoned()) - self->unwind(); - else - self->complete(); - } - - // Only giving the segment up destroys it: a closed executor - // destroying the posted unwind, or a holder with no owner to post - // to destroying it in place. - static void on_destroy(frame_cb* p) noexcept - { - static_cast(p->data)->unwind(); + complete(); } // The segment was given up: destroy its frames, and complete // stopped, since it has no result to deliver. - void unwind() noexcept + void on_abandon() noexcept { aw_.reset(); ex::set_stopped(std::move(rcvr_)); @@ -500,7 +468,7 @@ struct awaitable_op_state // there is no in-band disposition; token state is the // only cancellation signal available for these rows. aw_->await_resume(); - if(env_.stop_token.stop_requested()) + if(this->env_.stop_token.stop_requested()) ex::set_stopped( std::move(rcvr_)); else @@ -536,7 +504,7 @@ struct awaitable_op_state else { auto result = aw_->await_resume(); - if(env_.stop_token.stop_requested()) + if(this->env_.stop_token.stop_requested()) ex::set_stopped( std::move(rcvr_)); else @@ -594,8 +562,7 @@ struct awaitable_op_state fa = alloc.resource(); } - env_ = await_context{io_ex, st, fa}; - env_.owner = &owner_; + auto h = this->bind_chain(io_ex, st, fa); if(aw_->await_ready()) { @@ -603,20 +570,12 @@ struct awaitable_op_state return; } - cb_.resume = &on_resume; - cb_.destroy = &on_destroy; - cb_.data = this; - - auto h = std::coroutine_handle<>::from_address( - static_cast(&cb_)); - owner_.bind(h, io_ex); - // Not a real coroutine caller, so symmetric transfer // must be driven by hand: any non-noop handle (our own // frame on immediate completion, or a wrapped task's // handle that still needs to run) has to be resumed // explicitly or nothing ever completes. - auto resumed = detail::call_await_suspend(&*aw_, h, &env_); + auto resumed = detail::call_await_suspend(&*aw_, h, &this->env_); if(resumed != std::noop_coroutine()) resumed.resume(); } diff --git a/example/awaitable-sender/read_op.hpp b/example/awaitable-sender/read_op.hpp index 94f4fd47e..11f62c212 100644 --- a/example/awaitable-sender/read_op.hpp +++ b/example/awaitable-sender/read_op.hpp @@ -12,7 +12,7 @@ #include "awaitable_sender_base.hpp" -#include +#include #include #include #include @@ -45,9 +45,6 @@ class read_op : public awaitable_sender_base std::error_code ec_{}; bool immediate_ = false; - await_context const* env_ = nullptr; - continuation cont_{}; - // Stop-wait mode: a coroutine owning a waker nobody wakes, so // it completes only when the environment's stop token fires // (with error::canceled). The waker lives in the coroutine @@ -100,9 +97,7 @@ class read_op : public awaitable_sender_base { if(stop_task_) return stop_task_->await_suspend(h, env); - env_ = env; - cont_ = continuation{h, nullptr, env->owner}; - env_->executor.post(cont_); + env->executor.post(env->park(h)); return std::noop_coroutine(); } @@ -137,9 +132,6 @@ class counted_read_op std::size_t n_ = 0; std::size_t* n_out_ = nullptr; - await_context const* env_ = nullptr; - continuation cont_{}; - public: /// Create an op with a scripted `(ec, n)` completion that /// reports `n` through `*n_out`. @@ -162,9 +154,7 @@ class counted_read_op std::coroutine_handle<> h, await_context const* env) { - env_ = env; - cont_ = continuation{h, nullptr, env->owner}; - env_->executor.post(cont_); + env->executor.post(env->park(h)); return std::noop_coroutine(); } diff --git a/example/awaitable-sender/tests.cpp b/example/awaitable-sender/tests.cpp index 18795c3ee..5e7fbedbf 100644 --- a/example/awaitable-sender/tests.cpp +++ b/example/awaitable-sender/tests.cpp @@ -184,18 +184,13 @@ struct ec_op { std::error_code ec_{}; - capy::await_context const* env_ = nullptr; - capy::continuation cont_{}; - bool await_ready() const noexcept { return false; } auto await_suspend( std::coroutine_handle<> h, capy::await_context const* env) { - env_ = env; - cont_ = capy::continuation{h}; - env_->executor.post(cont_); + env->executor.post(env->park(h)); return std::noop_coroutine(); } @@ -208,18 +203,13 @@ struct compound_op std::error_code ec_{}; std::size_t n_ = 0; - capy::await_context const* env_ = nullptr; - capy::continuation cont_{}; - bool await_ready() const noexcept { return false; } auto await_suspend( std::coroutine_handle<> h, capy::await_context const* env) { - env_ = env; - cont_ = capy::continuation{h}; - env_->executor.post(cont_); + env->executor.post(env->park(h)); return std::noop_coroutine(); } @@ -248,18 +238,13 @@ static_assert(capy::AwaitableSender); // 1-tuple-ec row exercised by async_waker). struct void_op { - capy::await_context const* env_ = nullptr; - capy::continuation cont_{}; - bool await_ready() const noexcept { return false; } auto await_suspend( std::coroutine_handle<> h, capy::await_context const* env) { - env_ = env; - cont_ = capy::continuation{h}; - env_->executor.post(cont_); + env->executor.post(env->park(h)); return std::noop_coroutine(); } @@ -270,18 +255,13 @@ struct void_op // error_code (the "other T" row of make_sigs). struct value_op { - capy::await_context const* env_ = nullptr; - capy::continuation cont_{}; - bool await_ready() const noexcept { return false; } auto await_suspend( std::coroutine_handle<> h, capy::await_context const* env) { - env_ = env; - cont_ = capy::continuation{h}; - env_->executor.post(cont_); + env->executor.post(env->park(h)); return std::noop_coroutine(); } @@ -292,18 +272,13 @@ struct value_op // awaitable_op_state's conditional try/catch -> set_error(exception_ptr). struct throwing_op { - capy::await_context const* env_ = nullptr; - capy::continuation cont_{}; - bool await_ready() const noexcept { return false; } auto await_suspend( std::coroutine_handle<> h, capy::await_context const* env) { - env_ = env; - cont_ = capy::continuation{h}; - env_->executor.post(cont_); + env->executor.post(env->park(h)); return std::noop_coroutine(); } @@ -636,9 +611,6 @@ struct alloc_probe_op { std::pmr::memory_resource** out_; - capy::await_context const* env_ = nullptr; - capy::continuation cont_{}; - bool await_ready() const noexcept { return false; } auto await_suspend( @@ -646,9 +618,7 @@ struct alloc_probe_op capy::await_context const* env) { *out_ = env->frame_allocator; - env_ = env; - cont_ = capy::continuation{h}; - env_->executor.post(cont_); + env->executor.post(env->park(h)); return std::noop_coroutine(); } @@ -849,11 +819,11 @@ void test_ensure_sender_lifts() CHECK(out.ch == channel::value); } -// Holds the continuation of what awaits it, as an I/O object does, +// Holds the chain of what awaits it, as an I/O object does, // until the test gives it up. struct held_op { - capy::continuation* slot_; + capy::coro_chain* slot_; std::latch* parked_; bool await_ready() const noexcept { return false; } @@ -862,8 +832,7 @@ struct held_op std::coroutine_handle<> h, capy::await_context const* env) noexcept { - slot_->h = h; - slot_->owner = env->owner; + *slot_ = env->park(h); parked_->count_down(); return std::noop_coroutine(); } @@ -871,7 +840,7 @@ struct held_op void await_resume() const noexcept {} }; -capy::task await_held(capy::continuation* slot, std::latch* parked) +capy::task await_held(capy::coro_chain* slot, std::latch* parked) { co_await held_op{slot, parked}; } @@ -881,7 +850,7 @@ void test_abandoned_task_completes_stopped() { capy::thread_pool pool(1); auto pool_ex = pool.get_executor(); - capy::continuation held; + capy::coro_chain held; std::latch parked(1); std::latch done(1); test_outcome out; @@ -891,16 +860,17 @@ void test_abandoned_task_completes_stopped() {pool_ex, {}}, &out, &done}); ex::start(op); WAIT_OR_DIE(parked); - capy::abandon(held); + held.reset(); WAIT_OR_DIE(done); CHECK(out.ch == channel::stopped); } -// Parks its caller without taking the chain's owner, so giving it up -// destroys the caller in place. +// Parks its caller on a standalone chain_state with no bound executor, +// so giving it up destroys the caller in place. struct unowned_held_op { - capy::continuation* slot_; + capy::chain_state* state_; + capy::coro_chain* slot_; std::latch* parked_; bool await_ready() const noexcept { return false; } @@ -909,7 +879,9 @@ struct unowned_held_op std::coroutine_handle<> h, capy::await_context const*) noexcept { - slot_->h = h; + state_->bind_root(h); + state_->set_leaf(h); + *slot_ = capy::coro_chain::from_address(state_); parked_->count_down(); return std::noop_coroutine(); } @@ -923,17 +895,18 @@ void test_unowned_abandon_completes_stopped() { capy::thread_pool pool(1); auto pool_ex = pool.get_executor(); - capy::continuation held; + capy::chain_state state; + capy::coro_chain held; std::latch parked(1); std::latch done(1); test_outcome out; auto op = ex::connect( - capy::as_sender(unowned_held_op{&held, &parked}), + capy::as_sender(unowned_held_op{&state, &held, &parked}), test_receiver{ {pool_ex, {}}, &out, &done}); ex::start(op); WAIT_OR_DIE(parked); - capy::abandon(held); + held.reset(); WAIT_OR_DIE(done); CHECK(out.ch == channel::stopped); } @@ -972,13 +945,13 @@ struct abandoning_executor } void on_work_started() const noexcept { inner_.on_work_started(); } void on_work_finished() const noexcept { inner_.on_work_finished(); } - std::coroutine_handle<> dispatch(capy::continuation& c) const + std::coroutine_handle<> dispatch(capy::coro_chain&& c) const { - return c.h; + return c.release_handle(); } - void post(capy::continuation& c) const + void post(capy::coro_chain&& c) const { - capy::abandon(c); + c.reset(); } }; diff --git a/example/cuda/datamovement/cuda_datamovement.hpp b/example/cuda/datamovement/cuda_datamovement.hpp index b00fc52e8..949ea00b0 100644 --- a/example/cuda/datamovement/cuda_datamovement.hpp +++ b/example/cuda/datamovement/cuda_datamovement.hpp @@ -10,7 +10,7 @@ #ifndef BOOST_CAPY_EXAMPLE_CUDA_DATAMOVEMENT_HPP #define BOOST_CAPY_EXAMPLE_CUDA_DATAMOVEMENT_HPP -#include +#include #include #include #include @@ -108,13 +108,13 @@ struct cuda_stream_awaiter class cuda_stream { cudaStream_t stream_ = nullptr; - continuation cont_; + coro_chain chain_; std::error_code error_; struct resume_ctx { executor_ref ex; - continuation* cont = nullptr; + coro_chain* chain = nullptr; }; resume_ctx ctx_; @@ -123,7 +123,7 @@ class cuda_stream on_complete(void* arg) { auto* ctx = static_cast(arg); - ctx->ex.post(*ctx->cont); + ctx->ex.post(std::move(*ctx->chain)); } // The paper hardcodes HostToDevice and describes memcpy_d2h as "the @@ -152,13 +152,13 @@ class cuda_stream self->error_ = make_cuda_error(err); return h; } - self->cont_.h = h; - self->cont_.owner = env->owner; - self->ctx_ = resume_ctx{env->executor, &self->cont_}; + self->chain_ = env->park(h); + self->ctx_ = resume_ctx{env->executor, &self->chain_}; err = cudaLaunchHostFunc( self->stream_, &on_complete, &self->ctx_); if(err != cudaSuccess) { + std::ignore = self->chain_.release_handle(); self->error_ = make_cuda_error(err); return h; } @@ -187,13 +187,13 @@ class cuda_stream std::coroutine_handle<> await_suspend(std::coroutine_handle<> h, await_context const* env) { - self->cont_.h = h; - self->cont_.owner = env->owner; - self->ctx_ = resume_ctx{env->executor, &self->cont_}; + self->chain_ = env->park(h); + self->ctx_ = resume_ctx{env->executor, &self->chain_}; auto err = cudaLaunchHostFunc( self->stream_, &on_complete, &self->ctx_); if(err != cudaSuccess) { + std::ignore = self->chain_.release_handle(); self->error_ = make_cuda_error(err); return h; } @@ -286,13 +286,13 @@ class cuda_device_stream cudaStream_t stream_; std::byte* d_ptr_; std::size_t offset_ = 0; - continuation cont_; + coro_chain chain_; std::error_code error_; struct resume_ctx { executor_ref ex; - continuation* cont = nullptr; + coro_chain* chain = nullptr; }; resume_ctx ctx_; @@ -301,7 +301,7 @@ class cuda_device_stream on_complete(void* arg) { auto* ctx = static_cast(arg); - ctx->ex.post(*ctx->cont); + ctx->ex.post(std::move(*ctx->chain)); } public: @@ -347,13 +347,13 @@ class cuda_device_stream } total += b.size(); } - self->cont_.h = h; - self->cont_.owner = env->owner; - self->ctx_ = resume_ctx{env->executor, &self->cont_}; + self->chain_ = env->park(h); + self->ctx_ = resume_ctx{env->executor, &self->chain_}; auto err = cudaLaunchHostFunc( self->stream_, &on_complete, &self->ctx_); if(err != cudaSuccess) { + std::ignore = self->chain_.release_handle(); self->error_ = make_cuda_error(err); return h; } diff --git a/example/cuda/notification-strategies/notification_strategies.hpp b/example/cuda/notification-strategies/notification_strategies.hpp index 2b202fff1..eb2c3289c 100644 --- a/example/cuda/notification-strategies/notification_strategies.hpp +++ b/example/cuda/notification-strategies/notification_strategies.hpp @@ -10,7 +10,7 @@ #ifndef BOOST_CAPY_EXAMPLE_CUDA_NOTIFICATION_STRATEGIES_HPP #define BOOST_CAPY_EXAMPLE_CUDA_NOTIFICATION_STRATEGIES_HPP -#include +#include #include #include @@ -67,7 +67,7 @@ struct poll_entry { cudaEvent_t event; executor_ref ex; - continuation* cont; + coro_chain* chain; std::error_code* ec; }; @@ -110,7 +110,7 @@ class poll_service } // Outside the lock: a post may unwind the waiter's chain. for(auto& e : ready_) - e.ex.post(*e.cont); + e.ex.post(std::move(*e.chain)); ready_.clear(); std::this_thread::yield(); } @@ -318,11 +318,11 @@ struct callback_awaitable struct resume_ctx { executor_ref ex; - continuation* cont = nullptr; + coro_chain* chain = nullptr; std::error_code* ec = nullptr; }; - continuation cont_; + coro_chain chain_; std::error_code ec_; resume_ctx ctx_; @@ -331,7 +331,7 @@ struct callback_awaitable { auto* c = static_cast(arg); *c->ec = std::error_code{}; - c->ex.post(*c->cont); + c->ex.post(std::move(*c->chain)); } bool await_ready() const noexcept @@ -342,13 +342,13 @@ struct callback_awaitable std::coroutine_handle<> await_suspend(std::coroutine_handle<> h, await_context const* env) { - cont_.h = h; - cont_.owner = env->owner; - ctx_ = resume_ctx{env->executor, &cont_, &ec_}; + chain_ = env->park(h); + ctx_ = resume_ctx{env->executor, &chain_, &ec_}; auto err = cudaLaunchHostFunc(stream, &on_complete, &ctx_); if(err != cudaSuccess) { // Could not register: resume inline so we never deadlock. + std::ignore = chain_.release_handle(); ec_ = make_cuda_error(err); return h; } @@ -386,7 +386,7 @@ class poll_awaitable { poll_service& svc_; cudaEvent_t event_; - continuation cont_; + coro_chain chain_; std::error_code ec_; public: @@ -404,9 +404,8 @@ class poll_awaitable std::coroutine_handle<> await_suspend(std::coroutine_handle<> h, await_context const* env) { - cont_.h = h; - cont_.owner = env->owner; - svc_.register_wait(poll_entry{event_, env->executor, &cont_, &ec_}); + chain_ = env->park(h); + svc_.register_wait(poll_entry{event_, env->executor, &chain_, &ec_}); return std::noop_coroutine(); } @@ -428,7 +427,7 @@ class deferred_sync_awaitable { sync_service& svc_; cudaStream_t stream_; - continuation cont_; + coro_chain chain_; std::error_code ec_; public: @@ -448,15 +447,14 @@ class deferred_sync_awaitable { auto ex = env->executor; auto stream = stream_; - cont_.h = h; - cont_.owner = env->owner; - svc_.post([ex, stream, ec = &ec_, cont = &cont_]() mutable + chain_ = env->park(h); + svc_.post([ex, stream, ec = &ec_, ch = &chain_]() mutable { auto err = cudaStreamSynchronize(stream); *ec = (err == cudaSuccess) ? std::error_code{} : make_cuda_error(err); - ex.post(*cont); + ex.post(std::move(*ch)); }); return std::noop_coroutine(); } diff --git a/example/custom-executor/custom_executor.cpp b/example/custom-executor/custom_executor.cpp index af5a1247c..10c341fdf 100644 --- a/example/custom-executor/custom_executor.cpp +++ b/example/custom-executor/custom_executor.cpp @@ -31,7 +31,7 @@ namespace capy = boost::capy; class run_loop : public capy::execution_context { // end::inherit[] - std::queue queue_; + std::queue queue_; std::thread::id owner_; public: @@ -48,23 +48,10 @@ class run_loop : public capy::execution_context { // Once torn down, the loop runs nothing, not even inline. owner_ = {}; - // Nothing will run these now: give them up, so their chains - // are unwound. An unwind posted here is given up in turn. - auto drain = [this] - { - while (!queue_.empty()) - { - auto c = queue_.front(); - queue_.pop(); - capy::abandon(c); - } - }; shutdown(); - drain(); + queue_ = {}; destroy(); - // Services give up their work in shutdown(), but anything a - // destructor posts anyway is still given up. - drain(); + queue_ = {}; } run_loop(run_loop const&) = delete; @@ -76,16 +63,15 @@ class run_loop : public capy::execution_context owner_ = std::this_thread::get_id(); while (!queue_.empty()) { - auto c = queue_.front(); + auto c = std::move(queue_.front()); queue_.pop(); - capy::safe_resume(c.h); + c.resume(); } } - // A copy keeps the owner, which abandon needs. - void enqueue(capy::continuation const& c) + void enqueue(capy::coro_chain&& c) { - queue_.push(c); + queue_.push(std::move(c)); } bool is_running_on_this_thread() const noexcept @@ -121,18 +107,18 @@ class run_loop::executor_type // tag::dispatch[] std::coroutine_handle<> dispatch( - capy::continuation& c) const + capy::coro_chain&& c) const { if (loop_->is_running_on_this_thread()) - return c.h; // resume inline - loop_->enqueue(c); + return c.release_handle(); // resume inline + loop_->enqueue(std::move(c)); return std::noop_coroutine(); // defer } // end::dispatch[] - void post(capy::continuation& c) const + void post(capy::coro_chain&& c) const { - loop_->enqueue(c); + loop_->enqueue(std::move(c)); } bool operator==(executor_type const& other) const noexcept diff --git a/example/early-quitter/checks.cpp b/example/early-quitter/checks.cpp index b33ca4257..17a219738 100644 --- a/example/early-quitter/checks.cpp +++ b/example/early-quitter/checks.cpp @@ -41,7 +41,7 @@ static queue_context g_ctx; // Queues every post; pump() runs them in order. struct queue_executor { - std::queue* q; + std::queue* q; bool* closed = nullptr; bool operator==(queue_executor const& o) const noexcept { return q == o.q; } @@ -49,19 +49,19 @@ struct queue_executor void on_work_started() const noexcept {} void on_work_finished() const noexcept {} - std::coroutine_handle<> dispatch(capy::continuation& c) const + std::coroutine_handle<> dispatch(capy::coro_chain&& c) const { - post(c); + post(std::move(c)); return std::noop_coroutine(); } // A closed executor gives up what is posted to it. - void post(capy::continuation& c) const + void post(capy::coro_chain&& c) const { if(closed && *closed) - capy::abandon(c); + c.reset(); else - q->push(c); + q->push(std::move(c)); } }; @@ -69,13 +69,13 @@ static_assert(capy::Executor); static_assert(capy::ContextRunnable>>); static_assert(capy::ContextRunnable>); -static void pump(std::queue& q) +static void pump(std::queue& q) { while(!q.empty()) { - auto c = q.front(); + auto c = std::move(q.front()); q.pop(); - c.h.resume(); + c.resume(); } } @@ -89,13 +89,10 @@ struct counter struct yield_awaitable { - capy::continuation c_; bool await_ready() const noexcept { return false; } void await_suspend(std::coroutine_handle<> h, capy::await_context const* env) { - c_.h = h; - c_.owner = env->owner; - env->executor.post(c_); + env->executor.post(env->park(h)); } void await_resume() const noexcept {} }; @@ -133,7 +130,7 @@ struct outcome }; template -static void launch(std::queue& q, std::stop_token st, +static void launch(std::queue& q, std::stop_token st, outcome& o, Q quitter_, bool* closed = nullptr) { queue_executor ex{&q, closed}; @@ -163,7 +160,7 @@ static quitter> two_yields() static void value_without_stop() { - std::queue q; + std::queue q; std::stop_source ss; outcome o; launch(q, ss.get_token(), o, two_yields()); @@ -206,7 +203,7 @@ static quitter> top(capy::async_waker& w, int& down, reach& r) // The stop ends three quitters at once; none resumes, all unwind. static void deep_stop_while_suspended() { - std::queue q; + std::queue q; std::stop_source ss; capy::async_waker w; outcome o; @@ -237,7 +234,7 @@ static quitter starts_then_waits( // With no hook in the launcher, the body runs up to its first co_await. static void stop_before_start() { - std::queue q; + std::queue q; std::stop_source ss; ss.request_stop(); capy::async_waker w; @@ -266,7 +263,7 @@ static quitter> ready_then_yield( // A result that completed is delivered; the stop lands at the next await. static void ready_success_then_stop_delivers() { - std::queue q; + std::queue q; std::stop_source ss; outcome o; int got = 0; @@ -283,7 +280,7 @@ static void ready_success_then_stop_delivers() // A canceled result with the stop pending ends the quitter there. static void ready_canceled_then_stop_stops() { - std::queue q; + std::queue q; std::stop_source ss; outcome o; int got = 0; @@ -319,7 +316,7 @@ static quitter> stop_then_probe(std::stop_source& ss, bool& touched) // so nothing (a lock, a buffer) is acquired only to be dropped. static void stop_pending_leaves_operation_untouched() { - std::queue q; + std::queue q; std::stop_source ss; outcome o; bool touched = false; @@ -351,7 +348,7 @@ static quitter> early_throw(std::stop_source& ss, bool& caught, // An exception from an early await_resume is not a stop: the body gets it. static void early_exception_reaches_body() { - std::queue q; + std::queue q; std::stop_source ss; outcome o; bool caught = false, reached = false; @@ -379,7 +376,7 @@ static quitter> wake_then_wait( // The wake has queued the gate; the stop arrives before it runs. static void stop_after_wake_before_gate() { - std::queue q; + std::queue q; std::stop_source ss; capy::async_waker w; outcome o; @@ -428,7 +425,7 @@ static quitter> outer_quitter( // A task between quitters receives canceled as a value and decides. static void task_between_quitters() { - std::queue q; + std::queue q; std::stop_source ss; capy::async_waker w; outcome o; @@ -469,7 +466,7 @@ static quitter> catches_child(bool& caught) static void exception_propagates() { - std::queue q; + std::queue q; std::stop_source ss; outcome o; bool caught = false; @@ -486,7 +483,7 @@ static void exception_propagates() // it: the chain is torn down from its owner, and no handler runs. static void teardown_through_closed_executor() { - std::queue q; + std::queue q; std::stop_source ss; capy::async_waker w; outcome o; @@ -522,7 +519,7 @@ static capy::task> join_two( static void when_all_branches_stop() { - std::queue q; + std::queue q; std::stop_source ss; capy::async_waker a, b; int down = 0; diff --git a/example/early-quitter/quitter.hpp b/example/early-quitter/quitter.hpp index c84fce408..c445692fb 100644 --- a/example/early-quitter/quitter.hpp +++ b/example/early-quitter/quitter.hpp @@ -456,7 +456,6 @@ class [[nodiscard]] quitter /// Construct by taking the frame of `other`. quitter(quitter&& other) noexcept : h_(std::exchange(other.h_, nullptr)) - , lent_(std::exchange(other.lent_, false)) { } @@ -467,7 +466,6 @@ class [[nodiscard]] quitter { destroy_frame(); h_ = std::exchange(other.h_, nullptr); - lent_ = std::exchange(other.lent_, false); } return *this; } @@ -498,7 +496,7 @@ class [[nodiscard]] quitter */ auto await_resume() { - lent_ = false; + h_.promise().set_lent(false); auto& p = h_.promise(); if(p.ep_) std::rethrow_exception(p.ep_); @@ -517,7 +515,6 @@ class [[nodiscard]] quitter friend class quitter; std::coroutine_handle h_; - bool lent_ = false; explicit quitter(std::coroutine_handle h) noexcept : h_(h) @@ -533,7 +530,7 @@ class [[nodiscard]] quitter p.parent_ = parent; p.promise_type::base::set_continuation(cont); p.set_environment(env); - lent_ = true; + p.set_lent(true); return h_; } @@ -543,15 +540,13 @@ class [[nodiscard]] quitter { if(!h_) return; - if(lent_ && !h_.done()) + auto& p = h_.promise(); + if(p.stopped_) { - auto& p = h_.promise(); - auto* owner = p.environment()->owner; - if(!p.stopped_ && !(owner && owner->abandoned())) - std::terminate(); + std::exchange(h_, nullptr).destroy(); + return; } - std::exchange(h_, nullptr).destroy(); - lent_ = false; + promise_type::destroy_coro(std::exchange(h_, nullptr)); } }; diff --git a/example/gui-integration/gui_integration.cpp b/example/gui-integration/gui_integration.cpp index d52fed003..4d9ec378c 100644 --- a/example/gui-integration/gui_integration.cpp +++ b/example/gui-integration/gui_integration.cpp @@ -69,7 +69,7 @@ class gui_app : public capy::execution_context std::thread::id const gui_thread_ = std::this_thread::get_id(); std::mutex m_; std::condition_variable cv_; - std::deque queue_; + std::deque queue_; bool quit_ = false; bool closed_ = false; @@ -85,28 +85,24 @@ class gui_app : public capy::execution_context { // Once torn down, the app runs nothing, not even inline. closed_ = true; - // Nothing will run these now: give them up, so their chains - // are unwound. An unwind posted here is given up in turn. auto drain = [this] { for(;;) { - capy::continuation c; + capy::coro_chain c; { std::lock_guard lock(m_); if(queue_.empty()) return; - c = queue_.front(); + c = std::move(queue_.front()); queue_.pop_front(); } - capy::abandon(c); + c.reset(); } }; shutdown(); drain(); destroy(); - // Services give up their work in shutdown(), but anything a - // destructor posts anyway is still given up. drain(); } @@ -115,12 +111,11 @@ class gui_app : public capy::execution_context // Run a coroutine on the GUI thread. Callable from any thread and // never blocks the caller. - // A copy keeps the owner, which abandon needs. - void post_to_gui_thread(capy::continuation const& c) + void post_to_gui_thread(capy::coro_chain&& c) { { std::lock_guard lock(m_); - queue_.push_back(c); + queue_.push_back(std::move(c)); } cv_.notify_one(); } @@ -143,17 +138,17 @@ class gui_app : public capy::execution_context check(on_gui_thread(), "run() called off the GUI thread"); for(;;) { - capy::continuation c; + capy::coro_chain c; { std::unique_lock lock(m_); cv_.wait(lock, [this]{ return !queue_.empty() || quit_; }); if(queue_.empty()) return; // quit requested, nothing left to run - c = queue_.front(); + c = std::move(queue_.front()); queue_.pop_front(); } - capy::safe_resume(c.h); + c.resume(); } } // end::run[] @@ -197,17 +192,17 @@ class gui_app::executor_type void on_work_started() const noexcept {} void on_work_finished() const noexcept {} - std::coroutine_handle<> dispatch(capy::continuation& c) const + std::coroutine_handle<> dispatch(capy::coro_chain&& c) const { if(app_->runs_inline()) - return c.h; // resume inline by symmetric transfer - app_->post_to_gui_thread(c); + return c.release_handle(); // resume inline by symmetric transfer + app_->post_to_gui_thread(std::move(c)); return std::noop_coroutine(); } - void post(capy::continuation& c) const + void post(capy::coro_chain&& c) const { - app_->post_to_gui_thread(c); + app_->post_to_gui_thread(std::move(c)); } bool operator==(executor_type const& other) const noexcept @@ -329,7 +324,7 @@ struct show_dialog { dialog& dialog_; capy::await_context const* env_ = nullptr; - capy::continuation cont_ = {}; + capy::coro_chain chain_ = {}; std::string answer_ = {}; bool await_ready() const noexcept @@ -341,18 +336,17 @@ struct show_dialog std::coroutine_handle<> h, capy::await_context const* env) { env_ = env; - cont_.h = h; - cont_.owner = env->owner; + chain_ = env->park(h); dialog_.show([this](std::string answer) { answer_ = std::move(answer); // The toolkit's thread must not resume the coroutine - // itself. Handing the continuation to the executor is what + // itself. Handing the chain to the executor is what // puts the resumption back on the GUI thread. This is also // the last read of *this: the executor may resume the // coroutine -- and then destroy this awaitable -- before // this call returns. - env_->executor.post(cont_); + env_->executor.post(std::move(chain_)); }); return std::noop_coroutine(); } diff --git a/example/sender-bridge/sender_awaitable.hpp b/example/sender-bridge/sender_awaitable.hpp index 74872933d..64ae60614 100644 --- a/example/sender-bridge/sender_awaitable.hpp +++ b/example/sender-bridge/sender_awaitable.hpp @@ -10,7 +10,7 @@ #ifndef BOOST_CAPY_EXAMPLE_SENDER_AWAITABLE_HPP #define BOOST_CAPY_EXAMPLE_SENDER_AWAITABLE_HPP -#include +#include #include #include #include @@ -114,8 +114,8 @@ struct bridge_receiver beman::execution::receiver_t; result_variant* result_; - continuation cont_; - await_context const* env_; + coro_chain chain_; + await_context const* env_; auto get_env() const noexcept -> bridge_env { @@ -129,7 +129,7 @@ struct bridge_receiver result_->template emplace<1>( std::forward(args)...); // resume on the caller's executor - env_->executor.post(cont_); + env_->executor.post(std::move(chain_)); } // end::set_value[] @@ -159,7 +159,7 @@ struct bridge_receiver std::make_exception_ptr( std::forward(e))); } - env_->executor.post(cont_); + env_->executor.post(std::move(chain_)); } void set_stopped() && noexcept @@ -167,7 +167,7 @@ struct bridge_receiver constexpr auto idx = HasEc ? 4 : 3; result_->template emplace( stopped_t{}); - env_->executor.post(cont_); + env_->executor.post(std::move(chain_)); } }; @@ -262,7 +262,7 @@ struct [[nodiscard]] sender_awaitable beman::execution::connect( std::move(sndr_), receiver_type{ - &result_, {h, nullptr, env->owner}, env})); + &result_, env->park(h), env})); op_constructed_ = true; beman::execution::start( *std::launder( From 8184eeebaf0973b096800517f6be69ee008d362d Mon Sep 17 00:00:00 2001 From: Vinnie Falco Date: Sat, 5 Dec 2026 07:53:45 -0800 Subject: [PATCH 6/6] Update documentation and doc tests and retire old headers Update test/doc/ snippets, programs, and reference examples, AsciiDoc pages under doc/modules/ROOT/pages/, and header Doxygen references to use coro_chain, coro_chain_queue, and root_promise_base. Remove include/boost/capy/continuation.hpp and include/boost/capy/ex/abandon.hpp, and use fileURLToPath in doc/lint/doc-lint.mjs. --- doc/lint/doc-lint.mjs | 3 +- .../4.coroutines/4e.context-awaitable.adoc | 9 +- .../pages/4.coroutines/4f.cancellation.adoc | 2 +- .../ROOT/pages/4.coroutines/4j.lifetimes.adoc | 11 +- .../pages/8.examples/8n.custom-executor.adoc | 11 +- .../pages/8.examples/8q.gui-integration.adoc | 2 +- .../ROOT/pages/9.design/9k.Executor.adoc | 30 +-- .../pages/9.design/9q.WhyNotStdExecution.adoc | 2 +- doc/modules/ROOT/pages/glossary.adoc | 13 +- doc/modules/ROOT/pages/index.adoc | 12 +- .../ROOT/pages/reference-overview.adoc | 16 +- .../boost/capy/concept/context_awaitable.hpp | 10 +- .../boost/capy/concept/context_runnable.hpp | 5 +- .../boost/capy/concept/execution_context.hpp | 8 +- include/boost/capy/concept/executor.hpp | 20 +- include/boost/capy/continuation.hpp | 122 --------- include/boost/capy/ex/abandon.hpp | 243 ------------------ .../ex/context_awaitable_promise_base.hpp | 8 +- include/boost/capy/ex/strand.hpp | 2 +- include/boost/capy/ex/thread_pool.hpp | 2 +- include/boost/capy/io/write_now.hpp | 4 +- include/boost/capy/task.hpp | 6 +- include/boost/capy/test/run_blocking.hpp | 10 +- .../programs/4d_executors_executor_ref.cpp | 25 +- test/doc/programs/index_page_trace.cpp | 51 ++-- .../reference/ContextAwaitable.concept.cpp | 11 +- test/doc/reference/Executor.concept.cpp | 13 +- test/doc/reference/abandonable.record.cpp | 99 ------- test/doc/reference/any_executor.record.cpp | 19 +- test/doc/reference/await_context.record.cpp | 12 +- test/doc/reference/chain_queue.record.cpp | 38 +++ ...ation.record.cpp => coro_chain.record.cpp} | 11 +- test/doc/reference/executor_ref.record.cpp | 17 +- ...ecord.cpp => root_promise_base.record.cpp} | 41 +-- test/doc/reference/strand.record.cpp | 19 +- test/doc/snippets/4d_executors.cpp | 2 +- test/doc/snippets/4e_context_awaitable.cpp | 37 ++- test/doc/snippets/4f_cancellation.cpp | 22 +- test/doc/snippets/9k_executor.cpp | 38 ++- 39 files changed, 245 insertions(+), 761 deletions(-) delete mode 100644 include/boost/capy/continuation.hpp delete mode 100644 include/boost/capy/ex/abandon.hpp delete mode 100644 test/doc/reference/abandonable.record.cpp create mode 100644 test/doc/reference/chain_queue.record.cpp rename test/doc/reference/{continuation.record.cpp => coro_chain.record.cpp} (75%) rename test/doc/reference/{chain_owner.record.cpp => root_promise_base.record.cpp} (59%) diff --git a/doc/lint/doc-lint.mjs b/doc/lint/doc-lint.mjs index 7f7f757b4..70defa840 100644 --- a/doc/lint/doc-lint.mjs +++ b/doc/lint/doc-lint.mjs @@ -84,8 +84,9 @@ // import fs from 'node:fs'; import path from 'node:path'; +import { fileURLToPath } from 'node:url'; -const ROOT = path.resolve(path.dirname(new URL(import.meta.url).pathname), '..'); +const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); // An optional CLI arg overrides which pages tree gets walked, so a self-test // can point this at a throwaway fixture tree instead of the real corpus. // A6/D2's nav.adoc is unaffected — those checks are orthogonal to what a diff --git a/doc/modules/ROOT/pages/4.coroutines/4e.context-awaitable.adoc b/doc/modules/ROOT/pages/4.coroutines/4e.context-awaitable.adoc index 456cd31c2..a28b7da91 100644 --- a/doc/modules/ROOT/pages/4.coroutines/4e.context-awaitable.adoc +++ b/doc/modules/ROOT/pages/4.coroutines/4e.context-awaitable.adoc @@ -49,7 +49,7 @@ This signature receives: ** cpp:await_context::executor[env->executor]: The caller's executor for dispatching completions ** cpp:await_context::stop_token[env->stop_token]: A stop token for cooperative cancellation ** cpp:await_context::frame_allocator[env->frame_allocator]: An optional xref:glossary.adoc#frame-allocator[frame allocator] -** cpp:await_context::owner[env->owner]: The xref:glossary.adoc#owner[owner] of the chain, which teardown uses to xref:glossary.adoc#abandon[abandon] it +** cpp:await_context::park[env->park(h)]: Parks `h` in the chain's root state and returns an owning cpp:coro_chain[] Following the convention of awaiters in {cpp}, the function returns `void`, `bool`, or a coroutine handle. cpp:ContextAwaitable[] gives the exact requirements. @@ -125,9 +125,8 @@ include::example$snippets/4e_context_awaitable.cpp[tag=my_awaitable] The key points: 1. Store the `await_context` as a pointer (`await_context const*`), never a copy. The functions that start a task guarantee the `await_context` outlives the awaitable's operation. -2. To resume the caller, wrap its handle in a cpp:continuation[] and pass that to the executor's `post` (or `dispatch`). These take a `continuation&`, not a raw `coroutine_handle`. Store the `continuation` in the awaitable so it keeps a stable address until the executor dequeues and resumes it. The executor links continuations intrusively, so a temporary would dangle. -3. Set the continuation's `owner` to `env->owner` before anything else can hold it. An executor that shuts down passes the continuations it holds to cpp:abandon[]. The owner lets cpp:abandon[] unwind the whole chain. Without it, only the awaiting frame is destroyed, and the frames above it hold a destroyed frame. -4. Respect the stop token for cancellation +2. To resume the caller, call `env->park(h)` to obtain an owning cpp:coro_chain[] and pass it to the executor's `post` (or `dispatch`). Store the `coro_chain` in the awaitable until completion. If the awaitable or executor is torn down before resuming, `~coro_chain()` unwinds the whole chain from its root automatically. +3. Respect the stop token for cancellation [#stop-callbacks-must-post-not-resume] === Stop Callbacks Must Post, Not Resume @@ -156,7 +155,7 @@ For a production implementation of the claim, read the source of cpp:async_waker == Running a Custom I/O Awaitable -This awaitable produces a value and resumes the caller by posting its cpp:continuation[] through the caller's executor: +This awaitable produces a value and resumes the caller by posting its cpp:coro_chain[] through the caller's executor: [source,cpp] ---- diff --git a/doc/modules/ROOT/pages/4.coroutines/4f.cancellation.adoc b/doc/modules/ROOT/pages/4.coroutines/4f.cancellation.adoc index e9a2d6435..48ff0d113 100644 --- a/doc/modules/ROOT/pages/4.coroutines/4f.cancellation.adoc +++ b/doc/modules/ROOT/pages/4.coroutines/4f.cancellation.adoc @@ -161,7 +161,7 @@ include::example$snippets/4f_cancellation.cpp[tag=access_stop_token,indent=0] `std::coroutine_handle::destroy()` is the {cpp}20 primitive that frees a xref:glossary.adoc#coroutine-frame[coroutine frame]. It is not a cancellation mechanism. It has the same flaw as forceful thread interruption. It tears the coroutine down at its suspension point. The destructors of live locals run, but the coroutine gets no chance to finish pending I/O or run the code that follows. -Capy exposes cpp:task::handle[handle]`()` so that the functions that start tasks (cpp:run_async[], cpp:run[]) and custom integrations can dispatch coroutines through xref:glossary.adoc#executor[executors]. Calling `destroy()` on such a handle while a parent awaits the coroutine produces undefined behavior. The parent still holds the frame and destroys it again. A holder that must give up a suspended coroutine for good passes its xref:glossary.adoc#continuation[continuation] to cpp:abandon[] instead. An xref:glossary.adoc#execution-context[execution context] being torn down is one such holder. cpp:abandon[] unwinds the chain from the top on its owner's executor. +Capy exposes cpp:task::handle[handle]`()` so that the functions that start tasks (cpp:run_async[], cpp:run[]) and custom integrations can dispatch coroutines through xref:glossary.adoc#executor[executors]. Calling `destroy()` on such a handle while a parent awaits the coroutine produces undefined behavior. The parent still holds the frame and destroys it again. A holder that must give up a suspended coroutine for good resets or destroys its cpp:coro_chain[] instead. An xref:glossary.adoc#execution-context[execution context] being torn down is one such holder. `~coro_chain()` unwinds the chain from the top on its owner's executor. The rule: diff --git a/doc/modules/ROOT/pages/4.coroutines/4j.lifetimes.adoc b/doc/modules/ROOT/pages/4.coroutines/4j.lifetimes.adoc index abd1ff9e5..404a2ead3 100644 --- a/doc/modules/ROOT/pages/4.coroutines/4j.lifetimes.adoc +++ b/doc/modules/ROOT/pages/4.coroutines/4j.lifetimes.adoc @@ -125,9 +125,8 @@ An awaitable is given an cpp:await_context[] pointer in `await_suspend`. The environment belongs to the owner of the awaitable's segment, described in <<_who_owns_a_suspended_coroutine,Who Owns a Suspended Coroutine>>. It lives until the awaitable's coroutine resumes or is unwound, so the awaitable can keep -the pointer. The cpp:continuation[] it hands to an executor must keep a stable -address until the executor runs it. It therefore belongs in the awaitable, not -on the stack. +the pointer. The cpp:coro_chain[] returned by `env->park(h)` owns the suspended +chain until the executor runs it or tears it down. xref:4.coroutines/4e.context-awaitable.adoc#_implementing_custom_contextawaitables[Implementing a Custom I/O Awaitable] lists these rules, and the rules for stop callbacks. @@ -145,10 +144,10 @@ The coroutine that started the segment is its _owner_. It is suspended above the segment until the segment's top task finishes. -While the chain is suspended, whatever it waits on holds its xref:glossary.adoc#continuation[continuation]: an +While the chain is suspended, whatever it waits on holds its cpp:coro_chain[]: an executor's queue, a xref:glossary.adoc#strand[strand], a mutex, a pending I/O operation. Normally the holder resumes it. A holder that will never resume it, because it is being torn -down, passes the continuation to cpp:abandon[] instead. The segment's owner +down, resets or destroys the cpp:coro_chain[] instead. The segment's owner then destroys the segment from its top frame down, on its own executor, and passes the unwind to the segment above. Nothing in an abandoned chain is resumed: no code after a suspension point runs, no result is delivered, and @@ -231,7 +230,7 @@ include::example$snippets/4j_lifetimes.cpp[tag=shutdown_order,indent=0] | The storage outlives the operation; await it, do not store it. | Awaitable -| Keep the `await_context` pointer; keep the `continuation` in the awaitable. +| Keep the `await_context` pointer; keep the `coro_chain` in the awaitable. | Suspended coroutine | Its holder resumes it or abandons it; never `destroy()` an awaited handle. diff --git a/doc/modules/ROOT/pages/8.examples/8n.custom-executor.adoc b/doc/modules/ROOT/pages/8.examples/8n.custom-executor.adoc index 0d2b6596b..4c8a2b58a 100644 --- a/doc/modules/ROOT/pages/8.examples/8n.custom-executor.adoc +++ b/doc/modules/ROOT/pages/8.examples/8n.custom-executor.adoc @@ -37,11 +37,10 @@ The destructor tears the loop down in five steps: . Reset `owner_`, so `dispatch` no longer resumes anything inline. . Call `shutdown()`, so each service gives up its work. -. Drain the queue, giving up each queued cpp:continuation[] with cpp:abandon[]. The drain also takes work posted while it runs. +. Clear `queue_`, so each queued cpp:coro_chain[] is destroyed and unwinds its chain in place. . Call `destroy()`. No service may be created after this call. -. Drain once more, for any work a service destructor posts anyway. +. Clear `queue_` once more, for any work a service destructor posts anyway. -The queue holds copies of each continuation, and each copy carries the owner that cpp:abandon[] needs. xref:4.coroutines/4j.lifetimes.adoc#_shutdown_ordering[Shutdown Ordering] describes what abandoning a chain does. === The Executor Concept @@ -50,8 +49,8 @@ The nested `executor_type` must provide: * cpp:Executor::context[context()] -- returns a reference to the owning cpp:execution_context[] * cpp:Executor::on_work_started[on_work_started()] / cpp:Executor::on_work_finished[on_work_finished()] -- work-tracking hooks -* `dispatch(c)` -- resume immediately if already on this context, otherwise enqueue. Takes a cpp:continuation[]`&` and returns `std::coroutine_handle<>`. -* `post(c)` -- always enqueue for later execution. Takes a `continuation&`. +* `dispatch(c)` -- resume immediately if already on this context, otherwise enqueue. Takes a cpp:coro_chain[]`&&` and returns `std::coroutine_handle<>`. +* `post(c)` -- always enqueue for later execution. Takes a `coro_chain&&`. * cpp:Executor::operator==[+operator==+] -- compare two executors for identity [source,cpp] @@ -66,7 +65,7 @@ include::example$custom-executor/custom_executor.cpp[tag=concept_check] include::example$custom-executor/custom_executor.cpp[tag=dispatch,indent=0] ---- -`dispatch` takes a `continuation&` and checks whether the caller is already running on the loop's thread. If so, it returns `c.h` directly for inline resumption via xref:glossary.adoc#symmetric-transfer[symmetric transfer]. Otherwise it enqueues a copy of `c` and returns `noop_coroutine` so the caller continues without blocking. +`dispatch` takes a `coro_chain&&` and checks whether the caller is already running on the loop's thread. If so, it returns `c.release_handle()` directly for inline resumption via xref:glossary.adoc#symmetric-transfer[symmetric transfer]. Otherwise it enqueues `std::move(c)` and returns `noop_coroutine` so the caller continues without blocking. `post` always enqueues, even if already on the right thread. diff --git a/doc/modules/ROOT/pages/8.examples/8q.gui-integration.adoc b/doc/modules/ROOT/pages/8.examples/8q.gui-integration.adoc index 5cb5d5e33..2548c7fd4 100644 --- a/doc/modules/ROOT/pages/8.examples/8q.gui-integration.adoc +++ b/doc/modules/ROOT/pages/8.examples/8q.gui-integration.adoc @@ -158,7 +158,7 @@ The xref:glossary.adoc#completion-handler[completion handler] runs on the GUI th The stand-in exists to prove the contract, not to model a toolkit. Five pieces change when the toolkit is real, and the rest does not: -* `post_to_gui_thread` forwards to the toolkit's own post operation, and the receiving side calls cpp:safe_resume[] on the handle. Work still queued when the loop is torn down is given up with cpp:abandon[], so its chain unwinds instead of leaking. +* `post_to_gui_thread` forwards to the toolkit's own post operation, and the receiving side calls `c.resume()`. Work still queued when the loop is torn down is destroyed via `~coro_chain()`, so its chain unwinds instead of leaking. * `gui_app::run` disappears. The toolkit already owns a loop, such as `QApplication::exec`, `g_main_loop_run`, or `wxApp::OnRun`. * `gui_app::quit` forwards to the toolkit's own quit, such as `QCoreApplication::quit`, `g_main_loop_quit`, or `wxAppConsole::ExitMainLoop`. * `label` becomes a real widget. Its thread check is the part the toolkit does not do for you. diff --git a/doc/modules/ROOT/pages/9.design/9k.Executor.adoc b/doc/modules/ROOT/pages/9.design/9k.Executor.adoc index 36bf69d8a..aaf70113e 100644 --- a/doc/modules/ROOT/pages/9.design/9k.Executor.adoc +++ b/doc/modules/ROOT/pages/9.design/9k.Executor.adoc @@ -11,11 +11,11 @@ The formal definition lives in the reference at cpp:Executor[]. An cpp:Executor[ === `dispatch(c)`: Execute If Safe -If the executor determines it is safe (e.g., the current thread is already associated with the executor's context), returns `c.h` for xref:glossary.adoc#symmetric-transfer[symmetric transfer]. Otherwise, posts the xref:glossary.adoc#continuation[continuation] for later execution and returns `std::noop_coroutine()`. The caller uses the returned handle for symmetric transfer from `await_suspend`, or calls `.resume()` at the event loop pump level. +If the executor determines it is safe (e.g., the current thread is already associated with the executor's context), returns `c.release_handle()` for xref:glossary.adoc#symmetric-transfer[symmetric transfer]. Otherwise, posts the cpp:coro_chain[] for later execution and returns `std::noop_coroutine()`. The caller uses the returned handle for symmetric transfer from `await_suspend`, or calls `.resume()` at the event loop pump level. === `post(c)` -- Always Queue -Queues the continuation for later execution without ever executing it inline. It returns without waiting for the continuation to run. The continuation is linked into the executor's internal queue via its cpp:continuation::reserved[reserved] slot, so no per-post heap allocation occurs. +Queues the cpp:coro_chain[] for later execution without ever executing it inline. It returns without waiting for the continuation to run. The chain state in the root promise carries an intrusive queue link, so no per-post heap allocation occurs. === `context()` -- Access the Execution Context @@ -49,7 +49,7 @@ Capy retains the core elements of this model: Capy removes or changes: - **`defer`.** Dropped entirely. See <>. -- **Function object submission.** Asio executors accept arbitrary callables. Capy executors accept cpp:continuation[]`&` -- a xref:glossary.adoc#coroutine-handle[coroutine handle] wrapped with an intrusive queue pointer. This removes the need for allocator-aware function erasure, eliminates per-post heap allocation, and enables a simpler, cheaper xref:glossary.adoc#type-erased[type-erased] wrapper (cpp:executor_ref[]). +- **Function object submission.** Asio executors accept arbitrary callables. Capy executors accept cpp:coro_chain[]`&&` -- an 8-byte move-only RAII handle to a suspended coroutine chain. This removes the need for allocator-aware function erasure, eliminates per-post heap allocation, and enables a simpler, cheaper xref:glossary.adoc#type-erased[type-erased] wrapper (cpp:executor_ref[]). - **cpp:Executor::dispatch[dispatch] return type.** Asio's `dispatch` returns void. Capy's cpp:Executor::dispatch[dispatch] returns `std::coroutine_handle<>` for symmetric transfer. See <>. [[why-dispatch-returns-handle]] @@ -119,9 +119,9 @@ When a completing task's `final_suspend` awaiter returns the parent's coroutine Corosio confirms this in practice: its entire I/O layer -- sockets, acceptors, timers, resolvers, signals -- across all five backends (epoll, kqueue, io_uring, IOCP, select) uses only cpp:Executor::dispatch[dispatch] and cpp:Executor::post[post]. No code path requires `defer`. -== Why `continuation`, Not Raw `coroutine_handle<>` +== Why `coro_chain`, Not Raw `coroutine_handle<>` -The executor accepts cpp:continuation[]`&` rather than `std::coroutine_handle<>`. A cpp:continuation[] wraps the handle with a pointer-sized cpp:continuation::reserved[reserved] slot that the executor commandeers as its queue link, enabling zero-allocation queuing, and the cpp:continuation::owner[owner] that cpp:abandon[] uses to unwind the chain when the coroutine is given up instead of resumed: +The executor accepts cpp:coro_chain[]`&&` rather than `std::coroutine_handle<>`. A cpp:coro_chain[] is an 8-byte move-only RAII handle to the chain state stored in the segment's root promise, providing an intrusive queue link for zero-allocation queuing and automatic RAII unwinding if the chain is given up instead of resumed: [source,cpp] ---- @@ -130,13 +130,13 @@ include::example$snippets/9k_executor.cpp[tag=continuation_struct] This design has three consequences: -- **Zero-allocation posting.** The thread pool links the cpp:continuation[] directly into its work queue via cpp:continuation::reserved[reserved]. No `new work(h)` per post. The queue node is embedded in the thing being queued -- the awaitable, combinator state, or trampoline promise that owns the continuation. +- **Zero-allocation posting.** The thread pool links the cpp:coro_chain[] directly into its work queue through cpp:chain_queue[]. No `new work(h)` per post. The queue node lives in the root promise that owns the segment. -- **Type erasure remains possible.** cpp:executor_ref[] wraps any executor behind a uniform vtable. The vtable function pointers accept cpp:continuation[]`&`, which is a concrete type. No templates on promise type are needed. +- **Type erasure remains possible.** cpp:executor_ref[] wraps any executor behind a uniform vtable. The vtable function pointers accept cpp:coro_chain[]`&&`, which is a concrete type. No templates on promise type are needed. -- **I/O operation structures stay simple.** Every I/O awaitable embeds a cpp:continuation[] for the caller's handle and an cpp:executor_ref[] for the executor. Both are non-templated, keeping xref:glossary.adoc#io-backend[I/O backend] code non-generic and out of headers. +- **I/O operation structures stay simple.** Every I/O awaitable embeds a cpp:coro_chain[] for the caller's chain and an cpp:executor_ref[] for the executor. Both are non-templated, keeping xref:glossary.adoc#io-backend[I/O backend] code non-generic and out of headers. -The handle within the cpp:continuation[] is still type-erased (`std::coroutine_handle<>`) for the same reasons that applied before: executor implementations are independent of coroutine internals, and the type-erased handle provides exactly the right interface (`resume()` and nothing else). +The leaf handle within the chain is still type-erased (`std::coroutine_handle<>`) for the same reasons that applied before: executor implementations are independent of coroutine internals, and the handle provides the exact resumption interface needed. == Why Nothrow Copy and Move @@ -171,7 +171,7 @@ These operations are public, not private with friendship. The reason is extensib Once a context's cpp:execution_context::shutdown[shutdown()] has begun, it runs no more work. Its executors stay valid until the context is destroyed: -- cpp:Executor::dispatch[dispatch] and cpp:Executor::post[post] never run the coroutine they are given. The executor passes the continuation to cpp:abandon[], at once or no later than the context's destruction, so the chain is unwound by its owner. +- cpp:Executor::dispatch[dispatch] and cpp:Executor::post[post] never run the coroutine they are given. The executor resets or destroys the cpp:coro_chain[], at once or no later than the context's destruction, so the chain is unwound from its root. - cpp:Executor::on_work_started[on_work_started], cpp:Executor::on_work_finished[on_work_finished], copy, comparison and cpp:Executor::context[context()] remain valid. Calling any member after the context is destroyed is undefined behavior. @@ -240,7 +240,7 @@ The executor concept is designed around a single use case: I/O completion dispat === Capture at Initiation -When a coroutine `co_await`s an I/O awaitable, the awaitable's `await_suspend` receives the caller's handle and executor. The awaitable embeds a cpp:continuation[] for the caller's handle: +When a coroutine `co_await`s an I/O awaitable, the awaitable's `await_suspend` receives the caller's handle and executor. The awaitable parks the handle in a cpp:coro_chain[] member: [source,cpp] ---- @@ -249,18 +249,18 @@ include::example$snippets/9k_executor.cpp[tag=capture_at_initiation,indent=0] === Resume at Completion -When the I/O completes (from the reactor thread for epoll, the completion port for IOCP, or the select loop), the awaitable resumes the embedded continuation through the stored executor. Posting it, as below, is the simplest valid choice: +When the I/O completes (from the reactor thread for epoll, the completion port for IOCP, or the select loop), the awaitable resumes the chain through the stored executor. Posting it, as below, is the simplest valid choice: [source,cpp] ---- include::example$snippets/9k_executor.cpp[tag=dispatch_at_completion,indent=0] ---- -No heap allocation occurs, because the continuation is embedded in the awaitable, which is alive for the duration of the suspension. A worker thread dequeues the continuation and resumes its handle. cpp:thread_pool[] does this through cpp:safe_resume[]. +No heap allocation occurs, because the queue node lives in the segment's root promise. A worker thread dequeues the cpp:coro_chain[] and calls `c.resume()`. === Platform Independence -Corosio dispatches instead, so the continuation resumes inline when the completion arrives on the context's own thread. This pattern is identical across all five Corosio backends: epoll and io_uring (Linux), kqueue (BSD/macOS), IOCP (Windows), and select (portable fallback). The executor concept and cpp:executor_ref[] provide the abstraction that makes this possible. The backend-specific code deals with I/O readiness or completion notification. The executor-specific code deals with coroutine scheduling. +Corosio dispatches instead, so the chain resumes inline when the completion arrives on the context's own thread. This pattern is identical across all five Corosio backends: epoll and io_uring (Linux), kqueue (BSD/macOS), IOCP (Windows), and select (portable fallback). The executor concept and cpp:executor_ref[] provide the abstraction that makes this possible. The backend-specific code deals with I/O readiness or completion notification. The executor-specific code deals with coroutine scheduling. NOTE: For the TLS save/restore protocol required around `.resume()` calls (cpp:safe_resume[]), including which two call sites are deliberately exempt, see xref:4.coroutines/4h.allocators.adoc#_tls_preservation[TLS Preservation]. @@ -281,6 +281,6 @@ include::example$snippets/9k_executor.cpp[tag=minimal_executor] == Summary -The cpp:Executor[] concept provides cpp:Executor::dispatch[dispatch] and cpp:Executor::post[post] for coroutine scheduling, work tracking for event loop lifetime, and cpp:Executor::context[context()] for service access. The design descends from Asio's executor model but is adapted for coroutines: `defer` is replaced by symmetric transfer, function objects are replaced by cpp:continuation[]`&` for zero-allocation intrusive queuing, and cpp:Executor::dispatch[dispatch] returns `std::coroutine_handle<>` for symmetric transfer. +The cpp:Executor[] concept provides cpp:Executor::dispatch[dispatch] and cpp:Executor::post[post] for coroutine scheduling, work tracking for event loop lifetime, and cpp:Executor::context[context()] for service access. The design descends from Asio's executor model but is adapted for coroutines: `defer` is replaced by symmetric transfer, function objects are replaced by cpp:coro_chain[]`&&` for zero-allocation intrusive queuing, and cpp:Executor::dispatch[dispatch] returns `std::coroutine_handle<>` for symmetric transfer. cpp:executor_ref[] type-erases any executor into two pointers, enabling platform-independent I/O completion dispatch with zero allocation and predictable cache behavior. The capture-at-initiation / resume-at-completion pattern is the fundamental use case the concept serves. \ No newline at end of file diff --git a/doc/modules/ROOT/pages/9.design/9q.WhyNotStdExecution.adoc b/doc/modules/ROOT/pages/9.design/9q.WhyNotStdExecution.adoc index 582765248..7b0c6e4d0 100644 --- a/doc/modules/ROOT/pages/9.design/9q.WhyNotStdExecution.adoc +++ b/doc/modules/ROOT/pages/9.design/9q.WhyNotStdExecution.adoc @@ -119,7 +119,7 @@ Adopting Capy does not mean leaving senders behind. Bridges run in both directio | Scheduling primitive | `schedule()` returns a sender -| cpp:Executor::dispatch[dispatch] and cpp:Executor::post[post] take a cpp:continuation[] +| cpp:Executor::dispatch[dispatch] and cpp:Executor::post[post] take a cpp:coro_chain[] | Where a coroutine resumes | Transferred back to the task's scheduler diff --git a/doc/modules/ROOT/pages/glossary.adoc b/doc/modules/ROOT/pages/glossary.adoc index 67e21bb0c..77618ea45 100644 --- a/doc/modules/ROOT/pages/glossary.adoc +++ b/doc/modules/ROOT/pages/glossary.adoc @@ -16,9 +16,10 @@ This glossary defines terms used throughout the Capy documentation. [[abandon]]Abandon:: To give up a suspended coroutine that its holder cannot resume, for example -when the execution context or strand holding it is destroyed. The coroutine's -segment is unwound from its owner without any frame delivering a result. See -cpp:abandon[] and xref:4.coroutines/4j.lifetimes.adoc[Lifetime and Ownership]. +when the execution context or strand holding it is destroyed. Destroying or +resetting the coroutine's cpp:coro_chain[] unwinds its segment from its owner +without any frame delivering a result. See cpp:coro_chain[] and +xref:4.coroutines/4j.lifetimes.adoc[Lifetime and Ownership]. [[affinity]]Affinity:: The binding of a coroutine to a specific executor. A coroutine with affinity @@ -87,8 +88,8 @@ xref:4.coroutines/4e.context-awaitable.adoc[The ContextAwaitable Protocol]. [[continuation]]Continuation:: The code that runs after an asynchronous operation completes. In Capy it is -always a suspended coroutine, whose handle is wrapped in a cpp:continuation[] -that executors can queue without allocating. +always a suspended coroutine chain owned by a move-only cpp:coro_chain[] +handle that executors can queue without allocating. [[coroutine]]Coroutine:: A function that can suspend and resume execution. Uses the `co_await`, @@ -197,7 +198,7 @@ others instead of blocking their threads. See cpp:async_mutex[] and xref:4.corou [[owner]]Owner:: The coroutine that started a segment. It stays suspended above the segment until the segment's top task finishes, and it unwinds the segment if the -segment is abandoned. See cpp:chain_owner[]. +segment is abandoned. See cpp:root_promise_base[]. == P diff --git a/doc/modules/ROOT/pages/index.adoc b/doc/modules/ROOT/pages/index.adoc index dc0b7c2b8..7a8e84d9d 100644 --- a/doc/modules/ROOT/pages/index.adoc +++ b/doc/modules/ROOT/pages/index.adoc @@ -221,9 +221,7 @@ In the diagram, you write the `run_async` participant and the transfers between * A function that starts tasks creates the environment: an executor, a stop token, a frame allocator, and an owner. It must set the frame allocator before the task's frame is allocated. xref:4.coroutines/4h.allocators.adoc#two-call-rationale[Frame Allocators] explains why cpp:run_async[] uses two calls for this. -* The function must also own the xref:glossary.adoc#segment[segment] that it starts, by binding a cpp:chain_owner[], so that a holder can abandon the segment. - It waits for the segment by awaiting cpp:abandonable[], which tells it whether the segment completed or was unwound. - The alternative is to make sure that nothing awaits a coroutine that could be abandoned. +* The function must also own the xref:glossary.adoc#segment[segment] that it starts, by deriving its promise from cpp:root_promise_base[] and calling `bind_chain`, so that a holder can abandon the segment. cpp:run_async[], cpp:run[] on another executor, and each branch of cpp:when_all[] and cpp:when_any[] own their segments already. * To store an executor without its type, use cpp:executor_ref[]. @@ -244,8 +242,8 @@ In the diagram, you write the I/O awaitable, and sometimes the I/O backend and t Its `await_suspend` receives the xref:glossary.adoc#coroutine-handle[coroutine handle] and the cpp:await_context[]. * Keep the executor from the environment. When the operation completes, resume the coroutine through that executor. - Wrap the handle in a cpp:continuation[] that lives in the awaitable, and pass it to cpp:Executor::post[post] or cpp:Executor::dispatch[dispatch]. - Copy the `owner` of the environment into cpp:continuation::owner[owner], so that the chain can be abandoned while the coroutine waits. + Park the handle via `env->park(h)` to obtain a cpp:coro_chain[], and pass it to cpp:Executor::post[post] or cpp:Executor::dispatch[dispatch]. + If the awaitable is torn down without resuming, destroying or resetting the cpp:coro_chain[] unwinds the chain automatically. Never call `resume()` on the handle directly. * Register a `std::stop_callback` on the stop token of the environment. The callback runs on the thread that requests the stop. @@ -254,8 +252,8 @@ In the diagram, you write the I/O awaitable, and sometimes the I/O backend and t Only one of them may resume the coroutine, so each one must first win an atomic claim. * An executor implements the cpp:Executor[] concept. Its `context()` returns the cpp:execution_context[] that created it. - An event loop that runs coroutines resumes them with cpp:safe_resume[], so that each coroutine keeps its own frame allocator. -* An execution context that is destroyed with work still queued passes each queued xref:glossary.adoc#continuation[continuation] to cpp:abandon[] instead of resuming it. + An event loop that runs coroutines resumes each queued cpp:coro_chain[] with `c.resume()`, which restores the coroutine's frame allocator automatically. +* An execution context that is destroyed with work still queued destroys or resets each queued cpp:coro_chain[] instead of resuming it. * To start Capy tasks from another event loop, use cpp:run_async[] with an executor for that loop. Read next: diff --git a/doc/modules/ROOT/pages/reference-overview.adoc b/doc/modules/ROOT/pages/reference-overview.adoc index ecf80a0bc..029ea93f0 100644 --- a/doc/modules/ROOT/pages/reference-overview.adoc +++ b/doc/modules/ROOT/pages/reference-overview.adoc @@ -86,7 +86,7 @@ See xref:4.coroutines/4c.launching.adoc[Starting Coroutines] and xref:4.coroutin An executor dispatches or posts continuations to its execution context. An execution context, such as cpp:thread_pool[], provides executors bound to its own resources. cpp:strand[] serializes the coroutines dispatched through it. -Authors of custom executors queue cpp:continuation[] objects and resume their handles with cpp:safe_resume[]. +Authors of custom executors queue cpp:coro_chain[] objects (for example in cpp:chain_queue[] or cpp:work_queue[]) and resume them with `c.resume()`. An execution context that owns worker threads can label them for debuggers with cpp:set_current_thread_name[]. See xref:4.coroutines/4d.executors.adoc[Executors and Execution Contexts] and xref:8.examples/8n.custom-executor.adoc[Custom Executor]. @@ -98,7 +98,7 @@ See xref:4.coroutines/4d.executors.adoc[Executors and Execution Contexts] and xr | cpp:Executor[], cpp:ExecutionContext[] | Types -| cpp:execution_context[], cpp:thread_pool[], cpp:strand[], cpp:executor_ref[], cpp:any_executor[], cpp:work_guard[], cpp:continuation[] +| cpp:execution_context[], cpp:thread_pool[], cpp:strand[], cpp:executor_ref[], cpp:any_executor[], cpp:work_guard[], cpp:coro_chain[], cpp:chain_queue[], cpp:work_item[], cpp:work_queue[] | Functions | cpp:get_system_context[], cpp:make_work_guard[], cpp:set_current_thread_name[] @@ -189,10 +189,9 @@ See xref:4.coroutines/4h.allocators.adoc[Frame Allocators]. [#chain-ownership-and-abandonment] == Chain Ownership and Abandonment -Each xref:glossary.adoc#segment[segment] of a coroutine chain has a cpp:chain_owner[]. -A holder that can never resume a suspended coroutine gives it up with cpp:abandon[]. -Execution contexts call cpp:abandon[] on queued coroutines when they shut down, and so do strands when their execution context shuts down. -An owner waits for its segment by awaiting cpp:abandonable[], which tells it whether the segment completed or was unwound. +Each xref:glossary.adoc#segment[segment] of a coroutine chain is owned at its root (see cpp:root_promise_base[]) and held while suspended by a move-only cpp:coro_chain[]. +A holder that can never resume a suspended coroutine resets or destroys its cpp:coro_chain[]. +Execution contexts and strands unwind queued cpp:coro_chain[] items automatically when they shut down. Abandonment also travels up a chain: when a coroutine started by cpp:when_all[], cpp:when_any[] or cpp:run[] is abandoned, its caller is abandoned too. A destroyed cpp:async_mutex[] or other primitive instead resumes its waiters with a canceled error. See xref:4.coroutines/4j.lifetimes.adoc[Lifetime and Ownership]. @@ -202,10 +201,7 @@ See xref:4.coroutines/4j.lifetimes.adoc[Lifetime and Ownership]. | Kind | Names | Types -| cpp:chain_owner[], cpp:abandonable[] - -| Functions -| cpp:abandon[] +| cpp:coro_chain[], cpp:chain_queue[], cpp:chain_state[], cpp:frame_cb[], cpp:work_node[], cpp:work_item[], cpp:work_queue[], cpp:root_promise_base[], cpp:root_work_base[] |=== [#buffers] diff --git a/include/boost/capy/concept/context_awaitable.hpp b/include/boost/capy/concept/context_awaitable.hpp index 1931e7116..29e697b02 100644 --- a/include/boost/capy/concept/context_awaitable.hpp +++ b/include/boost/capy/concept/context_awaitable.hpp @@ -115,12 +115,10 @@ concept AwaitSuspendResult = type signature. _Teardown_: An awaitable that holds the coroutine for later, rather than - resuming it before returning, keeps it as a @ref continuation whose `owner` - is `env->owner`. The awaitable, or whatever holds the coroutine for it, - may be torn down first. It then passes that continuation to @ref abandon. - That call unwinds the chain from its owner. A continuation without an - owner is destroyed alone, leaving the frames above it holding a - destroyed frame. + resuming it before returning, parks it via `env->park(h)` and keeps the + returned @ref coro_chain. If the awaitable, or whatever holds the + coroutine for it, is torn down before resuming, destroying or resetting + that @ref coro_chain unwinds the chain from its root. _Lifetime_: The object of type @ref await_context pointed to by `env` remains valid for the duration of the async operation represented by diff --git a/include/boost/capy/concept/context_runnable.hpp b/include/boost/capy/concept/context_runnable.hpp index 92b7760d6..acbf590af 100644 --- a/include/boost/capy/concept/context_runnable.hpp +++ b/include/boost/capy/concept/context_runnable.hpp @@ -85,8 +85,9 @@ namespace capy { @li The object owns the frame, and destroying the object destroys it; a destroyed frame never destroys its continuation. A chain - given up with @ref abandon is unwound from its owner downward, - each object destroying the frame it owns. + whose @ref coro_chain is reset or destroyed without resuming is + unwound from its root downward, each object destroying the frame + it owns. @li Destroying or assigning over the object while an awaiting chain holds the frame calls `std::terminate`. The exception is a chain whose owner, from the environment passed to `set_environment`, diff --git a/include/boost/capy/concept/execution_context.hpp b/include/boost/capy/concept/execution_context.hpp index 1e21f1a89..77bba7bad 100644 --- a/include/boost/capy/concept/execution_context.hpp +++ b/include/boost/capy/concept/execution_context.hpp @@ -41,9 +41,9 @@ namespace capy { resources owned by the context. @li Executors referencing the context may be used only while the context exists. - @li Destroying the context abandons work submitted via associated - executors that has not started running, as @ref abandon - describes. + @li Destroying the context unwinds work submitted via associated + executors that has not started running, through @ref coro_chain + destruction. @par Conforming Signatures @@ -52,7 +52,7 @@ namespace capy { @par Example - `post` takes a `continuation&`, which no closure converts to; ordinary + `post` takes a `coro_chain&&`, which no closure converts to; ordinary callers reach it indirectly through `run_async` or similar combinators: @par !example example_2 diff --git a/include/boost/capy/concept/executor.hpp b/include/boost/capy/concept/executor.hpp index a4f83f055..f564e4395 100644 --- a/include/boost/capy/concept/executor.hpp +++ b/include/boost/capy/concept/executor.hpp @@ -125,17 +125,15 @@ class execution_context; Once `ctx.shutdown()` has begun, the context runs no more work. `dispatch` and `post` remain valid until the context is destroyed, but never run the coroutine they are given. Instead the executor - passes the continuation to @ref abandon, either at once or no later + resets or destroys the @ref coro_chain, either at once or no later than the context's destruction. A context does the same with the - coroutines it holds. An executor takes a continuation off its queue - before it resumes or abandons it. A queued copy keeps the - continuation's `owner`, which @ref abandon needs. An abandon made - inside `post` may unwind the chain before `post` returns. That - abandon is therefore the executor's last touch of the continuation. - It is also the last touch of the executor object, which may live in - a frame the unwind destroys. A `post` that throws has - neither queued nor abandoned the continuation; the caller still - holds it. Copy, comparison, `context()`, + chains it holds. An executor takes a @ref coro_chain off its queue + before it resumes or resets it. Resetting inside `post` may unwind + the chain before `post` returns. That reset is therefore the + executor's last touch of the @ref coro_chain, and of the executor + object, which may live in a frame the unwind destroys. A `post` that + throws has neither queued nor unwound the @ref coro_chain; the + caller still holds it. Copy, comparison, `context()`, `on_work_started`, and `on_work_finished` also remain valid until the context is destroyed. Calling any member after the context is destroyed is undefined behavior. @@ -151,7 +149,7 @@ class execution_context; @li A @ref task suspending. This includes @ref when_all and @ref when_any starting their children, and @ref run moving to its executor. - @li @ref abandon posting an unwind. + @li @ref coro_chain::reset posting an unwind. @li A join or a @ref run boundary resuming the coroutine awaiting it. @li @ref async_mutex, @ref async_event or @ref async_waker resuming a waiter. The trigger may be an unlock, a set, a wake, a stop diff --git a/include/boost/capy/continuation.hpp b/include/boost/capy/continuation.hpp deleted file mode 100644 index 914e19ec5..000000000 --- a/include/boost/capy/continuation.hpp +++ /dev/null @@ -1,122 +0,0 @@ -// -// Copyright (c) 2026 Michael Vandeberg -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// Official repository: https://github.com/cppalliance/capy -// - -#ifndef BOOST_CAPY_CONTINUATION_HPP -#define BOOST_CAPY_CONTINUATION_HPP - -#include - -#include - -namespace boost { -namespace capy { - -class chain_owner; - -/** Pair a coroutine handle with a scratch slot for allocation-free queuing. - - An executor links the continuation into its queue through the - scratch slot, so posting a coroutine needs no heap allocation. - - @par Fields - - @li `h` — the coroutine handle to resume. Set by the - code that creates or reuses the continuation (typically - an I/O awaitable or combinator). Read by the executor - when it dequeues the continuation. - - @li `reserved` — a pointer-sized scratch slot. Ordinary - users must not touch it. Authors of awaitable algorithms - (e.g. `async_mutex`, `async_semaphore`) may commandeer - it for their own node-based data structure. They may do - so **only before** the continuation is submitted to an - executor. - On submission the executor **clobbers** `reserved` to - link the continuation into its internal queue; the value - carries **no meaning** afterward. Once submitted, the - caller must not read or modify the continuation at all. - - @li `owner`: the @ref chain_owner of the chain segment the - coroutine belongs to, or null. @ref abandon reads it to - unwind the segment. - - @par Ownership and Lifetime - - The continuation is owned by the site that embeds it (an - I/O awaitable, combinator state, or trampoline promise). - The executor borrows it by reference for the duration of - the queue residency. - - A continuation must have a **stable address** while it is - linked into an executor's queue. It must not be moved, - destroyed, or enqueued in more than one queue concurrently. - - An author who needs a doubly-linked (or otherwise richer) - structure should hold a `continuation` as a member. Deriving - from it also works, because `continuation` is an aggregate. - Such an author should manage their own links, because - `reserved` is only a single pre-submission scratch slot. It - is no longer available once the continuation is submitted. - - @par Copy and Move - - Trivially copyable and movable (aggregate of a handle and - two pointers). However, copying or moving a queued - continuation produces a second object whose `reserved` slot - is stale, because the executor still links the original. Copy - and move are safe only when the continuation is not enqueued. - - @par Thread Safety - - A single continuation must not be accessed concurrently - without external synchronization. In practice, the - creating thread sets `h` and calls `executor.post(c)`; - the executor's worker thread later reads `h` and calls - `h.resume()`. The executor's internal locking provides - the necessary synchronization between these two accesses. - - @par Example - @par !example example - - @see @ref Executor, @ref executor_ref -*/ -struct continuation -{ - /** The coroutine handle to resume. - - Set by the code that creates or reuses the continuation, and read - by the executor when it dequeues it. - */ - std::coroutine_handle<> h; - - /** Pointer-sized scratch slot, available only before submission. - - Authors of awaitable algorithms may commandeer it for their own - node links until the continuation is submitted to an executor. On - submission the executor clobbers it to link the continuation into - its own queue, after which the value carries no meaning. See the - class description for the full contract. - */ - void* reserved = nullptr; - - /** The owner of the chain segment the coroutine belongs to. - - Set from the coroutine's @ref await_context when it is parked or - queued. A holder that gives the coroutine up passes this - continuation to @ref abandon, which unwinds the segment from its - owner. Null for a coroutine with no owner, such as an owner's own - continuation, which @ref abandon destroys directly. - */ - chain_owner* owner = nullptr; -}; - -} // namespace capy -} // namespace boost - -#endif diff --git a/include/boost/capy/ex/abandon.hpp b/include/boost/capy/ex/abandon.hpp deleted file mode 100644 index 819258b8d..000000000 --- a/include/boost/capy/ex/abandon.hpp +++ /dev/null @@ -1,243 +0,0 @@ -// -// Copyright (c) 2026 Steve Gerbino -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// Official repository: https://github.com/cppalliance/capy -// - -#ifndef BOOST_CAPY_EX_ABANDON_HPP -#define BOOST_CAPY_EX_ABANDON_HPP - -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -namespace boost { -namespace capy { - -/** Unwind a coroutine chain's segment when one of its coroutines is abandoned. - - A segment is a run of coroutines started together. It is the task - `run_async` starts and everything it awaits, a task `run` starts on - another executor, or one branch of `when_all` or `when_any`. Its - owner is the coroutine that started it, suspended above the - segment's top frame until that frame completes. Every coroutine in - the segment reaches the owner through its @ref await_context. - - When the holder of a suspended coroutine in the segment gives it up - with @ref abandon, the owner posts its own continuation to its - executor. There it unwinds the segment from the top. It destroys - the frame it awaits, which destroys the frames below it in turn. - The owner then finishes without delivering a result. An executor - that destroys the posted continuation instead, as a closed one does, - unwinds the segment the same way. - - @par Thread Safety - @ref abandon may be called from any thread. Only one holder can - abandon a segment, since it is suspended at one point; a repeated - call before the unwind runs does nothing. - - @par Example - @par !example example - - @see @ref abandon, @ref abandonable -*/ -class chain_owner -{ - std::atomic abandoned_{false}; - continuation self_; - executor_ref ex_; - -public: - /** Bind the owner to its coroutine and executor. - - Called by the owner before it starts the segment. - - @param self The owner's coroutine, resumed or destroyed to - unwind the segment. - - @param ex The executor the segment runs on. - */ - void bind(std::coroutine_handle<> self, executor_ref ex) noexcept - { - self_.h = self; - ex_ = ex; - } - - /// Check whether the segment has been abandoned. - bool abandoned() const noexcept - { - return abandoned_.load(std::memory_order_acquire); - } - - /** Unwind the segment on the owner's executor. - - Does nothing if the segment was already abandoned. Otherwise - posts the owner's continuation; nothing of the owner is touched - afterward, since the post may unwind and free it at once. - - @note A post that throws calls `std::terminate`. - */ - void abandon() noexcept - { - if(abandoned_.exchange(true, std::memory_order_acq_rel)) - return; - ex_.post(self_); - } -}; - -/** Give up a suspended coroutine for good. - - Called by the holder of a suspended coroutine that will never resume - it, such as an execution context, strand or primitive being torn - down. The owner of the coroutine's segment unwinds it on the owner's - executor. The unwind runs from the top frame down to this coroutine, - and no frame delivers a result. Ordinary cancellation does not use - this; it resumes the coroutine with an error instead. - - A continuation with no owner, such as an owner's own continuation, - is destroyed directly. - - After the call, the caller must not touch the coroutine, or anything - in its frame, again. - - @pre `c` refers to a suspended coroutine that the caller holds and - that nothing else will resume or abandon. If `c` has no owner, - nothing awaits the coroutine: destroying its frame alone would leave - any awaiting frame holding a destroyed one. - - @par Postconditions - The frames may already be destroyed when this returns, if the - owner's executor destroys posted work at once. - - @note The unwind runs on the owner's executor. That executor may - belong to another execution context than the caller's, and the - unwind may run after the caller's context is destroyed. A chain that - holds objects of the caller's context must therefore have finished - before that context is torn down. - - @note Each frame is destroyed by the destructor of the frame that - awaits it. The unwind therefore uses stack in proportion to how - deeply the chain's coroutines are nested. - - @param c The continuation of the coroutine given up. -*/ -inline void -abandon(continuation& c) noexcept -{ - if(c.owner) - c.owner->abandon(); - else if(c.h) - c.h.destroy(); -} - -/** Await an awaitable on behalf of a segment owner. - - An owner, a coroutine that binds a @ref chain_owner and starts a - segment beneath it, waits for that segment by awaiting this. It is - resumed either when the awaitable completes or to unwind the - segment after an @ref abandon. In the second case the awaitable - never completed, so there is no result to read. The result is - empty, or `false` for an awaitable with no result. The owner must - then destroy the awaitable without reading it. - - The awaitable is referenced, not copied, so the caller keeps it - alive until the `co_await` completes. Its `await_resume` must - return a move-constructible object or `void`: the result is moved - into a `std::optional`, which cannot hold a reference. - - @pre The awaiting coroutine's @ref await_context names, as its - `owner`, the @ref chain_owner bound to that coroutine. - - @par Exception Safety - An exception from the awaitable's `await_ready`, `await_suspend` or - `await_resume` propagates unchanged. - - @note Awaited from a promise built on - @ref context_awaitable_promise_base, as an owner usually is, an - exception from `await_ready` or `await_suspend` calls - `std::terminate` instead. - - @par Example - @par !example example - - @see @ref chain_owner, @ref abandon -*/ -template -class abandonable -{ - A& a_; - chain_owner* owner_ = nullptr; - -public: - /// The awaitable's own `await_resume` result. - using result_type = decltype(std::declval().await_resume()); - - /** Construct from the awaitable to wait for. - - @param a The awaitable. It is referenced, not copied. - */ - explicit abandonable(A& a) noexcept - : a_(a) - { - } - - /// Check whether the awaitable is already complete. - bool await_ready() - { - return a_.await_ready(); - } - - /** Suspend on the awaitable, remembering the segment owner. - - @param h The coroutine performing the `co_await`. - @param env The environment of that coroutine. - - @return The awaitable's own `await_suspend` result. - */ - template - auto await_suspend(H h, await_context const* env) - { - owner_ = env->owner; - return a_.await_suspend(h, env); - } - - /** Return the result, or nothing if the segment was abandoned. - - For an awaitable with no result this returns `bool` instead, - `false` when the segment was unwound. - - @return An engaged optional or `true`; empty or `false` if unwound. - */ - auto await_resume() - { - bool const unwinding = owner_ && owner_->abandoned(); - if constexpr(std::is_void_v) - { - if(unwinding) - return false; - a_.await_resume(); - return true; - } - else - { - if(unwinding) - return std::optional(); - return std::optional(a_.await_resume()); - } - } -}; - -} // namespace capy -} // namespace boost - -#endif diff --git a/include/boost/capy/ex/context_awaitable_promise_base.hpp b/include/boost/capy/ex/context_awaitable_promise_base.hpp index ccbcb8e46..30f6ea410 100644 --- a/include/boost/capy/ex/context_awaitable_promise_base.hpp +++ b/include/boost/capy/ex/context_awaitable_promise_base.hpp @@ -82,10 +82,10 @@ namespace capy { The object that awaits a coroutine, such as the parent's `task`, owns its frame. A chain is therefore destroyed from its top down, each frame freeing the one it awaits. The suspended coroutine at the - bottom is held by whoever will resume it: an operation, queue or - primitive. A holder that will never resume it calls @ref abandon, - which unwinds the chain's segment from its owner (see - @ref chain_owner) rather than destroying the bottom frame. + bottom is held as a @ref coro_chain by whoever will resume it: an + operation, queue or primitive. A holder that will never resume it + resets or destroys its @ref coro_chain, which unwinds the chain's + segment from its root rather than destroying the bottom frame. Destroying a frame that is still awaited, other than in that unwind, calls `std::terminate`. diff --git a/include/boost/capy/ex/strand.hpp b/include/boost/capy/ex/strand.hpp index 5b65d40d7..7a8402a4e 100644 --- a/include/boost/capy/ex/strand.hpp +++ b/include/boost/capy/ex/strand.hpp @@ -57,7 +57,7 @@ namespace capy { destroyed. Coroutines queued on the strand when its context shuts down are - passed to @ref abandon rather than resumed. + unwound via @ref coro_chain::reset rather than resumed. @par Thread Safety Distinct objects: Safe. diff --git a/include/boost/capy/ex/thread_pool.hpp b/include/boost/capy/ex/thread_pool.hpp index ac649b0d8..643ee393c 100644 --- a/include/boost/capy/ex/thread_pool.hpp +++ b/include/boost/capy/ex/thread_pool.hpp @@ -75,7 +75,7 @@ class BOOST_CAPY_DECL That happens during this destructor when the executor is this pool, and later when it belongs to another execution context. - See @ref chain_owner. + See @ref coro_chain. To let queued work finish first, call @ref join before the pool is destroyed. diff --git a/include/boost/capy/io/write_now.hpp b/include/boost/capy/io/write_now.hpp index 2a43a8819..98ff0f1ec 100644 --- a/include/boost/capy/io/write_now.hpp +++ b/include/boost/capy/io/write_now.hpp @@ -57,8 +57,8 @@ namespace capy { completed (i.e., the returned awaitable is fully consumed). Destroying the returned operation object while it is being awaited - calls `std::terminate`, except while its chain is unwound after an - @ref abandon. + calls `std::terminate`, except while its chain is unwound after + @ref coro_chain::reset. @par Thread Safety Distinct objects: Safe. diff --git a/include/boost/capy/task.hpp b/include/boost/capy/task.hpp index 5e342cbae..6c34de26f 100644 --- a/include/boost/capy/task.hpp +++ b/include/boost/capy/task.hpp @@ -289,7 +289,7 @@ struct [[nodiscard]] BOOST_CAPY_CORO_AWAIT_ELIDABLE /** Destroy the task and its coroutine frame if owned. @pre The frame is not lent: no parent is suspended awaiting - it, unless its chain is being unwound after an @ref abandon. + it, unless its chain is being unwound after @ref coro_chain::reset. Destroying a lent frame otherwise calls `std::terminate`; end a running chain by requesting stop, or by destroying its execution context. @@ -384,7 +384,7 @@ struct [[nodiscard]] BOOST_CAPY_CORO_AWAIT_ELIDABLE task is being awaited. The awaiting frame still holds the handle and destroys it again, which has undefined behavior. The operation, queue or primitive holding a suspended coroutine - gives it up by passing its continuation to @ref abandon. + gives it up by resetting or destroying its @ref coro_chain. The task's lifetime is normally managed by `run_async`, `run`, or the awaiting parent. For cooperative cancellation, use `std::stop_token`. @@ -453,7 +453,7 @@ struct [[nodiscard]] BOOST_CAPY_CORO_AWAIT_ELIDABLE @pre The frame being replaced is not lent: no parent is suspended awaiting it, unless its chain is being unwound after - an @ref abandon. Replacing a lent frame otherwise calls + @ref coro_chain::reset. Replacing a lent frame otherwise calls `std::terminate`. @pre `other` is not being awaited. Moving from a task whose diff --git a/include/boost/capy/test/run_blocking.hpp b/include/boost/capy/test/run_blocking.hpp index 824c7312a..c2919d44f 100644 --- a/include/boost/capy/test/run_blocking.hpp +++ b/include/boost/capy/test/run_blocking.hpp @@ -125,7 +125,7 @@ struct BOOST_CAPY_DECL blocking_executor Users do not interact with it directly. Coroutines still queued when the context is destroyed are - passed to @ref abandon rather than resumed. + unwound via @ref coro_chain::reset rather than resumed. @par Thread Safety The event loop runs on the thread that calls `run()`. @@ -202,12 +202,12 @@ class BOOST_CAPY_DECL blocking_context void run(); - /** Enqueue a continuation for processing. + /** Enqueue a chain for processing. - A copy is queued, so the owner it carries reaches @ref abandon - if the context is destroyed first. + The moved-in @ref coro_chain unwinds the chain if the context is + destroyed first. - @param c The continuation to enqueue. + @param c The chain to enqueue. */ void enqueue(coro_chain&& c); diff --git a/test/doc/programs/4d_executors_executor_ref.cpp b/test/doc/programs/4d_executors_executor_ref.cpp index 4a6ccc439..cc2f4435a 100644 --- a/test/doc/programs/4d_executors_executor_ref.cpp +++ b/test/doc/programs/4d_executors_executor_ref.cpp @@ -10,7 +10,7 @@ // Full program shown in pages/4.coroutines/4d.executors.adoc. -#include +#include #include #include #include @@ -19,24 +19,25 @@ #include #include +#include namespace capy = boost::capy; namespace { -capy::continuation parked; +capy::coro_chain parked; std::binary_semaphore parked_ready{0}; -// Suspends its coroutine and publishes the continuation so another +// Suspends its coroutine and publishes the chain so another // thread can schedule the resumption. struct park { bool await_ready() const noexcept { return false; } std::coroutine_handle<> await_suspend( - std::coroutine_handle<> h, capy::await_context const*) + std::coroutine_handle<> h, capy::await_context const* env) { - parked.h = h; + parked = env->park(h); parked_ready.release(); return std::noop_coroutine(); } @@ -50,20 +51,20 @@ capy::task parked_task() } // Launch a coroutine on the pool and block until it has parked, -// leaving its continuation ready to be scheduled. -capy::continuation& make_suspended_work(capy::thread_pool& pool) +// leaving its coro_chain ready to be scheduled. +capy::coro_chain make_suspended_work(capy::thread_pool& pool) { capy::run_async(pool.get_executor())(parked_task()); parked_ready.acquire(); - return parked; + return std::move(parked); } } // namespace // tag::full[] -void schedule_work(capy::executor_ref ex, capy::continuation& c) +void schedule_work(capy::executor_ref ex, capy::coro_chain c) { - ex.post(c); // Works with any executor + ex.post(std::move(c)); // Works with any executor } int main() @@ -72,8 +73,8 @@ int main() auto pool_ex = pool.get_executor(); capy::executor_ref ex = pool_ex; // Type erasure; pool_ex must outlive ex - capy::continuation& c = make_suspended_work(pool); // a coroutine parked on the pool - schedule_work(ex, c); + capy::coro_chain c = make_suspended_work(pool); // a coroutine parked on the pool + schedule_work(ex, std::move(c)); pool.join(); } // end::full[] diff --git a/test/doc/programs/index_page_trace.cpp b/test/doc/programs/index_page_trace.cpp index c2c86d649..75da6ac31 100644 --- a/test/doc/programs/index_page_trace.cpp +++ b/test/doc/programs/index_page_trace.cpp @@ -31,6 +31,7 @@ #include #include #include +#include #include namespace capy = boost::capy; @@ -48,7 +49,7 @@ std::queue> backend; class trace_loop : public capy::execution_context { - std::queue queue_; + std::queue queue_; public: class executor_type; @@ -58,36 +59,17 @@ class trace_loop : public capy::execution_context { } - // Nothing will run what is still queued: give it up, so its chain is - // unwound. Destroying a service, or unwinding a chain, can queue more - // work, so repeat until a drain finds nothing. ~trace_loop() { - auto drain = [this] - { - bool any = false; - while (!queue_.empty()) - { - auto c = queue_.front(); - queue_.pop(); - any = true; - capy::abandon(c); - } - return any; - }; shutdown(); - drain(); - do - { - destroy(); - } - while (drain()); + queue_ = {}; + destroy(); + queue_ = {}; } - // A copy keeps the owner, which abandon needs. - void enqueue(capy::continuation const& c) + void enqueue(capy::coro_chain&& c) { - queue_.push(c); + queue_.push(std::move(c)); } // Run queued coroutines. Poll the backend only when the queue is empty. @@ -102,10 +84,10 @@ class trace_loop : public capy::execution_context complete(); continue; } - auto c = queue_.front(); + auto c = std::move(queue_.front()); queue_.pop(); step("executor: resume"); - capy::safe_resume(c.h); + c.resume(); } } @@ -132,17 +114,17 @@ class trace_loop::executor_type void on_work_started() const noexcept {} void on_work_finished() const noexcept {} - std::coroutine_handle<> dispatch(capy::continuation& c) const + std::coroutine_handle<> dispatch(capy::coro_chain&& c) const { step("executor: dispatch"); - loop_->enqueue(c); + loop_->enqueue(std::move(c)); return std::noop_coroutine(); } - void post(capy::continuation& c) const + void post(capy::coro_chain&& c) const { step("executor: post"); - loop_->enqueue(c); + loop_->enqueue(std::move(c)); } bool operator==(executor_type const& other) const noexcept @@ -160,7 +142,7 @@ trace_loop::get_executor() noexcept // An I/O awaitable for a read that the fake backend completes with 5 bytes. struct read_awaitable { - capy::continuation cont_; + capy::coro_chain chain_; capy::executor_ref ex_; std::size_t bytes_ = 0; @@ -172,14 +154,13 @@ struct read_awaitable std::coroutine_handle<> await_suspend( std::coroutine_handle<> h, capy::await_context const* env) { - cont_.h = h; - cont_.owner = env->owner; + chain_ = env->park(h); ex_ = env->executor; step("I/O awaitable: start the operation"); backend.push([this] { step("I/O backend: the operation completes"); bytes_ = 5; - ex_.post(cont_); // never cont_.h.resume() + ex_.post(std::move(chain_)); }); step("I/O awaitable: suspend"); return std::noop_coroutine(); diff --git a/test/doc/reference/ContextAwaitable.concept.cpp b/test/doc/reference/ContextAwaitable.concept.cpp index 9124253e7..98d36db3d 100644 --- a/test/doc/reference/ContextAwaitable.concept.cpp +++ b/test/doc/reference/ContextAwaitable.concept.cpp @@ -25,6 +25,7 @@ #include #include #include +#include #include namespace capy = boost::capy; @@ -43,7 +44,7 @@ void start_my_io_op(std::stop_token, Completion&&) {} class my_awaitable { capy::await_context const* env_ = nullptr; - capy::continuation cont_; + capy::coro_chain chain_; std::error_code ec_ {}; public: @@ -52,13 +53,13 @@ class my_awaitable std::coroutine_handle<> await_suspend(std::coroutine_handle<> h, capy::await_context const* env) noexcept { - env_ = env; // store the pointer, never a copy - cont_ = capy::continuation{h}; + env_ = env; // store the pointer, never a copy + chain_ = env->park(h); auto completion = [this](std::error_code ec) noexcept { - ec_ = ec; // publish result; touch *this - env_->executor.post(cont_); // only before post, never after + ec_ = ec; // publish result; touch *this + env_->executor.post(std::move(chain_)); // only before post, never after }; start_my_io_op(env_->stop_token, completion); diff --git a/test/doc/reference/Executor.concept.cpp b/test/doc/reference/Executor.concept.cpp index 1d5d1fd7a..0fa0b059e 100644 --- a/test/doc/reference/Executor.concept.cpp +++ b/test/doc/reference/Executor.concept.cpp @@ -24,6 +24,7 @@ #include #include #include +#include #include namespace capy = boost::capy; @@ -50,15 +51,15 @@ class E } std::coroutine_handle<> dispatch( - capy::continuation& c ) const + capy::coro_chain&& c ) const { if( std::this_thread::get_id() == home_ ) - return c.h; // symmetric transfer - post( c ); + return c.release_handle(); // symmetric transfer + post( std::move(c) ); return std::noop_coroutine(); } - void post( capy::continuation& ) const + void post( capy::coro_chain&& ) const { // enqueue for later execution on this executor's context } @@ -79,8 +80,8 @@ class E void on_work_finished() const noexcept; std::coroutine_handle<> dispatch( - capy::continuation& c ) const; - void post( capy::continuation& c ) const; + capy::coro_chain&& c ) const; + void post( capy::coro_chain&& c ) const; bool operator==( E const& ) const noexcept; }; diff --git a/test/doc/reference/abandonable.record.cpp b/test/doc/reference/abandonable.record.cpp deleted file mode 100644 index 1cc144d1d..000000000 --- a/test/doc/reference/abandonable.record.cpp +++ /dev/null @@ -1,99 +0,0 @@ -// -// Copyright (c) 2026 Steve Gerbino -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// Official repository: https://github.com/cppalliance/capy -// - -// Reference examples for boost::capy::abandonable, injected into its documentation by -// doc/addons/extensions/reference-snippets.lua. Declared in: -// include/boost/capy/ex/abandon.hpp -// -// The tagged regions are what the reference renders; the includes, -// suppressions and namespaces around them are scaffolding. Each region gets -// its own namespace so that examples which reuse a name still compile. - -#include "../doc_warnings.hpp" - -#include - -#include -#include -#include - -namespace capy = boost::capy; - -namespace { - -namespace ex_1 { - -// A root coroutine that owns its segment, as a server's per-connection -// launcher does. The base hands env_ to each awaited operation. -struct owner_root -{ - struct promise_type - : capy::context_awaitable_promise_base - { - capy::chain_owner owner_; - capy::await_context env_; - - template - promise_type(capy::executor_ref ex, Args&&...) - : env_{ex, {}, capy::get_current_frame_allocator(), &owner_} - { - this->set_environment(&env_); - } - - owner_root get_return_object() - { - auto self = - std::coroutine_handle::from_promise(*this); - owner_.bind(self, env_.executor); - return {self}; - } - std::suspend_always initial_suspend() noexcept { return {}; } - std::suspend_never final_suspend() noexcept { return {}; } - void return_void() noexcept {} - void unhandled_exception() noexcept { std::terminate(); } - }; - - std::coroutine_handle h; - - owner_root(std::coroutine_handle h_) noexcept : h(h_) {} - owner_root(owner_root const&) = delete; - - // Once started, the frame frees itself when it finishes, or is - // destroyed by its executor when the segment is abandoned. - void start() - { - std::exchange(h, nullptr).resume(); - } - - // Only a root that never started is still ours to destroy. - ~owner_root() - { - if(h) - h.destroy(); - } -}; - -capy::task compute() { co_return 42; } - -// tag::example[] -// The body of a root coroutine whose promise binds a chain_owner and -// names it as the owner in the environment it hands to the task. -owner_root serve(capy::executor_ref, int& out) -{ - auto t = compute(); - auto r = co_await capy::abandonable(t); - if(!r) - co_return; // abandoned: leaving destroys t, which unwinds it - out = *r; -} -// end::example[] - -} // namespace ex_1 - -} // namespace diff --git a/test/doc/reference/any_executor.record.cpp b/test/doc/reference/any_executor.record.cpp index 3226f61a9..3eff6cb56 100644 --- a/test/doc/reference/any_executor.record.cpp +++ b/test/doc/reference/any_executor.record.cpp @@ -19,12 +19,7 @@ #include -#include -#include -#include -#include -#include -#include +#include namespace capy = boost::capy; @@ -32,19 +27,17 @@ namespace { namespace ex_1 { // tag::example[] -// c must stay at a stable address until the executor dequeues it, so -// the caller owns it -- typically as part of the awaitable or -// operation state that posts it, never as a callee-local temporary. -void dispatch_via_context(capy::thread_pool& ctx, capy::continuation& c) +void dispatch_via_context(capy::thread_pool& ctx, capy::coro_chain c) { capy::any_executor exec = ctx.get_executor(); if(exec) { auto& context = exec.context(); - // dispatch() may hand the continuation straight back for + (void)context; + // dispatch() may hand the leaf handle straight back for // symmetric transfer instead of enqueuing it, so the returned - // handle must be resumed or the continuation is dropped. - exec.dispatch(c).resume(); + // handle must be resumed. + exec.dispatch(std::move(c)).resume(); } } // end::example[] diff --git a/test/doc/reference/await_context.record.cpp b/test/doc/reference/await_context.record.cpp index 1baac4bf8..59950ef8a 100644 --- a/test/doc/reference/await_context.record.cpp +++ b/test/doc/reference/await_context.record.cpp @@ -27,22 +27,16 @@ namespace { namespace ex_1 { // tag::example[] -// An awaitable keeps the pointer, not a copy, and queues the -// coroutine for resumption through env->executor. +// An awaitable parks the coroutine through env->park(h) and posts the +// returned coro_chain through env->executor. struct my_awaitable { - capy::await_context const* env_ = nullptr; - capy::continuation cont_; - bool await_ready() const noexcept { return false; } std::coroutine_handle<> await_suspend( std::coroutine_handle<> h, capy::await_context const* env) { - env_ = env; - cont_.h = h; - cont_.owner = env->owner; - env->executor.post(cont_); + env->executor.post(env->park(h)); return std::noop_coroutine(); } diff --git a/test/doc/reference/chain_queue.record.cpp b/test/doc/reference/chain_queue.record.cpp new file mode 100644 index 000000000..211d25bd9 --- /dev/null +++ b/test/doc/reference/chain_queue.record.cpp @@ -0,0 +1,38 @@ +// +// Copyright (c) 2026 Steve Gerbino +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// Official repository: https://github.com/cppalliance/capy +// + +// Reference examples for boost::capy::chain_queue, injected into its documentation by +// doc/addons/extensions/reference-snippets.lua. Declared in: +// include/boost/capy/coro_chain.hpp +// +// The tagged regions are what the reference renders; the includes, +// suppressions and namespaces around them are scaffolding. Each region gets +// its own namespace so that examples which reuse a name still compile. + +#include "../doc_warnings.hpp" + +#include + +#include + +namespace capy = boost::capy; + +namespace { + +namespace ex_1 { +// tag::example[] +void drain_queue( capy::chain_queue& q ) +{ + while( auto c = q.pop() ) + c.resume(); +} +// end::example[] +} // namespace ex_1 + +} // namespace diff --git a/test/doc/reference/continuation.record.cpp b/test/doc/reference/coro_chain.record.cpp similarity index 75% rename from test/doc/reference/continuation.record.cpp rename to test/doc/reference/coro_chain.record.cpp index 9ec35440c..3792e4d31 100644 --- a/test/doc/reference/continuation.record.cpp +++ b/test/doc/reference/coro_chain.record.cpp @@ -7,9 +7,9 @@ // Official repository: https://github.com/cppalliance/capy // -// Reference examples for boost::capy::continuation, injected into its documentation by +// Reference examples for boost::capy::coro_chain, injected into its documentation by // doc/addons/extensions/reference-snippets.lua. Declared in: -// include/boost/capy/continuation.hpp +// include/boost/capy/coro_chain.hpp // // The tagged regions are what the reference renders; the includes, // suppressions and namespaces around them are scaffolding. Each region gets @@ -27,19 +27,14 @@ namespace { namespace ex_1 { // tag::example[] -// The awaitable embeds the continuation so its address stays stable struct yield_awaitable { - capy::continuation c; - bool await_ready() const noexcept { return false; } void await_suspend( std::coroutine_handle<> h, capy::await_context const* env ) { - c.h = h; - c.owner = env->owner; // lets a teardown abandon the whole segment - env->executor.post( c ); + env->executor.post( env->park( h ) ); } void await_resume() const noexcept {} diff --git a/test/doc/reference/executor_ref.record.cpp b/test/doc/reference/executor_ref.record.cpp index 447b8bf8e..86b117b2d 100644 --- a/test/doc/reference/executor_ref.record.cpp +++ b/test/doc/reference/executor_ref.record.cpp @@ -19,12 +19,7 @@ #include -#include -#include -#include -#include -#include -#include +#include namespace capy = boost::capy; @@ -32,17 +27,15 @@ namespace { namespace ex_1 { // tag::example[] -// my_continuation must stay at a stable address until the executor -// dequeues it, so it is owned by the caller, not by store_executor(). -void store_executor(capy::executor_ref ex, capy::continuation& my_continuation) +void store_executor(capy::executor_ref ex, capy::coro_chain my_chain) { if(ex) - ex.post(my_continuation); + ex.post(std::move(my_chain)); } -void use_thread_pool(capy::thread_pool& ctx, capy::continuation& my_continuation) +void use_thread_pool(capy::thread_pool& ctx, capy::coro_chain my_chain) { - store_executor(ctx.get_executor(), my_continuation); + store_executor(ctx.get_executor(), std::move(my_chain)); } // end::example[] } // namespace ex_1 diff --git a/test/doc/reference/chain_owner.record.cpp b/test/doc/reference/root_promise_base.record.cpp similarity index 59% rename from test/doc/reference/chain_owner.record.cpp rename to test/doc/reference/root_promise_base.record.cpp index 8661e3c99..7b74ecbe6 100644 --- a/test/doc/reference/chain_owner.record.cpp +++ b/test/doc/reference/root_promise_base.record.cpp @@ -7,9 +7,9 @@ // Official repository: https://github.com/cppalliance/capy // -// Reference examples for boost::capy::chain_owner, injected into its documentation by +// Reference examples for boost::capy::root_promise_base, injected into its documentation by // doc/addons/extensions/reference-snippets.lua. Declared in: -// include/boost/capy/ex/abandon.hpp +// include/boost/capy/ex/root_promise_base.hpp // // The tagged regions are what the reference renders; the includes, // suppressions and namespaces around them are scaffolding. Each region gets @@ -21,6 +21,7 @@ #include #include +#include namespace capy = boost::capy; @@ -28,54 +29,34 @@ namespace { namespace ex_1 { +// tag::example[] struct owner_root { - // tag::example[] - // An owner's promise binds its chain_owner and names it in the - // environment it hands to the segment it awaits. struct promise_type - : capy::context_awaitable_promise_base + : capy::root_promise_base { - capy::chain_owner owner_; - capy::await_context env_; - template promise_type(capy::executor_ref ex, Args&&...) - : env_{ex, {}, capy::get_current_frame_allocator(), &owner_} { - this->set_environment(&env_); + this->bind_chain( + std::coroutine_handle::from_promise(*this), + ex, {}, capy::get_current_frame_allocator()); } owner_root get_return_object() { - auto self = - std::coroutine_handle::from_promise(*this); - owner_.bind(self, env_.executor); - return {self}; + return {std::coroutine_handle::from_promise(*this)}; } + std::suspend_always initial_suspend() noexcept { return {}; } std::suspend_never final_suspend() noexcept { return {}; } void return_void() noexcept {} void unhandled_exception() noexcept { std::terminate(); } }; - // end::example[] std::coroutine_handle h; - - owner_root(std::coroutine_handle h_) noexcept : h(h_) {} - owner_root(owner_root const&) = delete; - - ~owner_root() - { - if(h) - h.destroy(); - } }; - -owner_root serve(capy::executor_ref) -{ - co_return; -} +// end::example[] } // namespace ex_1 diff --git a/test/doc/reference/strand.record.cpp b/test/doc/reference/strand.record.cpp index b975897d1..4f453ca54 100644 --- a/test/doc/reference/strand.record.cpp +++ b/test/doc/reference/strand.record.cpp @@ -19,12 +19,7 @@ #include -#include -#include -#include -#include -#include -#include +#include namespace capy = boost::capy; @@ -32,18 +27,14 @@ namespace { namespace ex_1 { // tag::example[] -// Continuations are linked intrusively into the strand's queue, so -// each must outlive its time there. The caller owns c1/c2/c3 -- -// typically as members of the awaitable or operation state that -// posts them, never as locals that go out of scope while enqueued. void post_three(capy::thread_pool& pool, - capy::continuation& c1, capy::continuation& c2, capy::continuation& c3) + capy::coro_chain c1, capy::coro_chain c2, capy::coro_chain c3) { capy::strand sd(pool.get_executor()); // CTAD deduces the executor type - sd.post(c1); - sd.post(c2); - sd.post(c3); + sd.post(std::move(c1)); + sd.post(std::move(c2)); + sd.post(std::move(c3)); } // end::example[] } // namespace ex_1 diff --git a/test/doc/snippets/4d_executors.cpp b/test/doc/snippets/4d_executors.cpp index 4c22a1ada..f8021ce3b 100644 --- a/test/doc/snippets/4d_executors.cpp +++ b/test/doc/snippets/4d_executors.cpp @@ -12,7 +12,7 @@ #include "../doc_warnings.hpp" -#include +#include #include #include #include diff --git a/test/doc/snippets/4e_context_awaitable.cpp b/test/doc/snippets/4e_context_awaitable.cpp index 3ca6aaa51..2b01458b9 100644 --- a/test/doc/snippets/4e_context_awaitable.cpp +++ b/test/doc/snippets/4e_context_awaitable.cpp @@ -13,7 +13,7 @@ #include "../doc_warnings.hpp" #include -#include +#include #include #include #include @@ -119,7 +119,7 @@ void store_result() {} struct my_awaitable { capy::await_context const* env_ = nullptr; - capy::continuation cont_; + capy::coro_chain chain_; result_type result_; bool await_ready() const noexcept @@ -132,12 +132,9 @@ struct my_awaitable { // Store pointer to environment, never copy env_ = env; - // Wrap the caller's handle in a continuation we own, so it stays - // at a stable address until the executor resumes it. - cont_.h = h; - // Lets whoever holds the continuation at teardown abandon the - // whole chain, not just this frame. - cont_.owner = env->owner; + // Park the caller's handle in the chain's root state and hold + // the returned coro_chain until the operation completes. + chain_ = env->park(h); // Start async operation... start_operation(); @@ -154,10 +151,9 @@ struct my_awaitable private: void on_completion() { - // Resume the caller on its executor. post() takes the - // continuation by reference and queues it; never resume inline + // Resume the caller on its executor. Never resume inline // from a completion callback (it may run on the wrong thread). - env_->executor.post(cont_); + env_->executor.post(std::move(chain_)); } }; // end::my_awaitable[] @@ -165,15 +161,14 @@ struct my_awaitable // tag::runnable_awaitable[] // A complete ContextAwaitable following the pattern above. It produces a // value, then resumes the caller on the caller's own executor by posting -// its continuation. A real one would do this from an async completion +// its coro_chain. A real one would do this from an async completion // callback; here the "operation" finishes immediately. struct add_awaitable { int a_; int b_; capy::await_context const* env_ = nullptr; - // Defaulted, so the call site supplies only a_ and b_. - capy::continuation cont_{}; + capy::coro_chain chain_{}; result_type result_{}; bool await_ready() const noexcept { return false; } @@ -182,10 +177,9 @@ struct add_awaitable std::coroutine_handle<> h, capy::await_context const* env) { env_ = env; - cont_.h = h; - cont_.owner = env->owner; // the executor holds it once posted + chain_ = env->park(h); // the executor holds it once posted result_ = a_ + b_; // the operation produced a value - env_->executor.post(cont_); // resume the caller on its executor + env_->executor.post(std::move(chain_)); // resume the caller on its executor return std::noop_coroutine(); } @@ -247,7 +241,7 @@ void start_foreign_op(std::function on_complete) struct foreign_bridge { capy::await_context const* env_ = nullptr; - capy::continuation cont_; + capy::coro_chain chain_; result_type result_; bool await_ready() const noexcept { return false; } @@ -256,16 +250,15 @@ struct foreign_bridge std::coroutine_handle<> h, capy::await_context const* env) { env_ = env; - cont_.h = h; // stable address; the executor links continuations intrusively - cont_.owner = env->owner; // so a holder can abandon the whole chain + chain_ = env->park(h); // Start the foreign operation. Its completion callback may run on // ANY thread, so it must not resume h directly. Instead it posts - // the continuation back through the caller's executor, restoring + // the chain back through the caller's executor, restoring // the same-executor invariant. start_foreign_op([this]() noexcept { store_result(); - env_->executor.post(cont_); + env_->executor.post(std::move(chain_)); }); return std::noop_coroutine(); diff --git a/test/doc/snippets/4f_cancellation.cpp b/test/doc/snippets/4f_cancellation.cpp index ea4c79e8e..1d72d69ee 100644 --- a/test/doc/snippets/4f_cancellation.cpp +++ b/test/doc/snippets/4f_cancellation.cpp @@ -20,7 +20,7 @@ #endif #include -#include +#include #include #include #include @@ -195,11 +195,11 @@ struct racy_read void operator()() const noexcept { self->canceled_ = true; - self->ex_.post(self->cont_); // even if the read completed + self->ex_.post(std::move(self->chain_)); // even if the read completed } }; - capy::continuation cont_; + capy::coro_chain chain_; capy::executor_ref ex_; bool canceled_ = false; std::optional> stop_cb_; @@ -209,8 +209,7 @@ struct racy_read std::coroutine_handle<> await_suspend( std::coroutine_handle<> h, capy::await_context const* env) { - cont_.h = h; - cont_.owner = env->owner; + chain_ = env->park(h); ex_ = env->executor; stop_cb_.emplace(env->stop_token, cancel_fn{this}); start_read(this); // the backend calls on_complete() later @@ -220,7 +219,7 @@ struct racy_read // Called by the I/O backend, on any thread, when the read finishes. void on_complete() noexcept { - ex_.post(cont_); // even if the stop callback posted already + ex_.post(std::move(chain_)); // even if the stop callback posted already } void await_resume() noexcept { stop_cb_.reset(); } @@ -277,7 +276,7 @@ struct read_op::awaiter }; read_op* op_; - capy::continuation cont_; + capy::coro_chain chain_; capy::executor_ref ex_; std::size_t bytes_ = 0; bool canceled_ = false; @@ -298,7 +297,7 @@ struct read_op::awaiter void arrive() noexcept { if (arrivals_.fetch_add(1, std::memory_order_acq_rel) == 1) - ex_.post(cont_); // last action: *this can be destroyed now + ex_.post(std::move(chain_)); // last action: *this can be destroyed now } bool await_ready() const noexcept { return false; } @@ -313,9 +312,7 @@ struct read_op::awaiter } // 1. Write everything the winner reads, before anyone can win. - // The owner lets a holder abandon the chain while it waits. - cont_.h = h; - cont_.owner = env->owner; + chain_ = env->park(h); ex_ = env->executor; op_->waiter_ = this; @@ -329,6 +326,7 @@ struct read_op::awaiter // 4. Claim a stop request that arrived during step 2. if (env->stop_token.stop_requested() && op_->claim()) { + std::ignore = chain_.release_handle(); canceled_ = true; return h; } @@ -336,7 +334,7 @@ struct read_op::awaiter // 5. Arrive. If the winner came first, resume now, on this // thread. Otherwise the winner posts the coroutine later. if (arrivals_.fetch_add(1, std::memory_order_acq_rel) == 1) - return h; + return chain_.release_handle(); return std::noop_coroutine(); } diff --git a/test/doc/snippets/9k_executor.cpp b/test/doc/snippets/9k_executor.cpp index 975f7245f..23ee4032c 100644 --- a/test/doc/snippets/9k_executor.cpp +++ b/test/doc/snippets/9k_executor.cpp @@ -13,8 +13,7 @@ #include "../doc_warnings.hpp" #include -#include -#include +#include #include #include #include @@ -25,6 +24,7 @@ #include #include #include +#include #include "test_suite.hpp" @@ -46,15 +46,15 @@ class dispatching_executor bool running_in_this_thread() const noexcept { return true; } } ctx_; - void post(capy::continuation&) const {} + void post(capy::coro_chain&&) const {} public: // tag::dispatch_impl[] - std::coroutine_handle<> dispatch(capy::continuation& c) const + std::coroutine_handle<> dispatch(capy::coro_chain&& c) const { if(ctx_.running_in_this_thread()) - return c.h; // symmetric transfer - post(c); + return c.release_handle(); // symmetric transfer + post(std::move(c)); return std::noop_coroutine(); } // end::dispatch_impl[] @@ -63,18 +63,16 @@ class dispatching_executor namespace continuation_def { // tag::continuation_struct[] -struct continuation +class coro_chain { - std::coroutine_handle<> h; - void* reserved = nullptr; - capy::chain_owner* owner = nullptr; + capy::chain_state* state_ = nullptr; }; // end::continuation_struct[] } // namespace continuation_def -static_assert(sizeof(continuation_def::continuation) - == sizeof(capy::continuation)); +static_assert(sizeof(continuation_def::coro_chain) + == sizeof(capy::coro_chain)); // Corosio's contexts implement work tracking over an atomic count; // this scaffolding reproduces just enough of that shape. @@ -131,11 +129,11 @@ class executor_ref static_assert(sizeof(layout_sketch::executor_ref) == sizeof(capy::executor_ref)); -// I/O awaitable shape: embeds a continuation for the caller's handle +// I/O awaitable shape: embeds a coro_chain for the caller's chain // and an executor_ref for completion dispatch. struct context_awaitable_sketch { - capy::continuation cont_; + capy::coro_chain chain_; capy::executor_ref ex_; // tag::capture_at_initiation[] @@ -144,7 +142,7 @@ struct context_awaitable_sketch std::coroutine_handle<> h, capy::await_context const* env) noexcept { - cont_.h = h; + chain_ = env->park(h); ex_ = env->executor; // ... initiate I/O operation ... return std::noop_coroutine(); @@ -155,7 +153,7 @@ struct context_awaitable_sketch { // tag::dispatch_at_completion[] // Timer fires or I/O completes: - ex_.post(cont_); + ex_.post(std::move(chain_)); // end::dispatch_at_completion[] } }; @@ -171,8 +169,8 @@ class my_executor void on_work_started() const noexcept; void on_work_finished() const noexcept; - std::coroutine_handle<> dispatch(capy::continuation& c) const; - void post(capy::continuation& c) const; + std::coroutine_handle<> dispatch(capy::coro_chain&& c) const; + void post(capy::coro_chain&& c) const; bool operator==(my_executor const&) const noexcept; }; @@ -185,8 +183,8 @@ struct executor_design_test void testDispatchReturnsHandle() { dispatching_executor ex; - capy::continuation c; - BOOST_TEST(ex.dispatch(c) == std::coroutine_handle<>()); + capy::coro_chain c; + BOOST_TEST(ex.dispatch(std::move(c)) == std::coroutine_handle<>()); } void testWorkCountReachesZero()