Starting Coroutines

Capy tasks are lazy: they do not execute until something drives them. Two mechanisms exist:

  • Awaiting: One coroutine awaits another (co_await task)

  • Starting: Non-coroutine code initiates execution (run_async)

Non-coroutine code must start the first task in a chain explicitly. How a Task Runs shows both mechanisms as a sequence diagram. Executors and Execution Contexts introduces the executors and thread pools this page uses.

When a task is awaited, the awaiting coroutine provides its execution environment. The environment holds an executor for dispatching completion and a stop token for cancellation. It also holds the frame allocator and the owner that teardown uses to unwind the chain.

run_async: Entry from Non-Coroutine Code

run_async takes an executor, creates the necessary context, and starts the task executing.

#include <boost/capy.hpp>
namespace capy = boost::capy;

capy::task<int> compute()
{
    co_return 42;
}

int main()
{
    capy::thread_pool pool;
    capy::run_async(pool.get_executor())(compute());
    // Task is now running on the thread pool

    pool.join();  // wait for outstanding work to complete
}

Two-Call Syntax

Call run_async with the executor first, then call the result with the task: run_async(executor)(task).

The two calls rely on C++17 evaluation order. C++17 guarantees that in the expression f(a)(b):

  1. f(a) is evaluated first, producing a callable

  2. b is evaluated second

  3. The callable is invoked with b

The task’s coroutine frame is allocated during step 2, and run_async sets up thread-local allocator state in step 1. The task inherits that allocator.

Construct the task as the direct argument of the two-call expression. Three patterns split the two calls apart, and the compiler catches only part of the first one.

Stored wrapper. Storing the result of run_async(executor) and calling it later as an lvalue does not compile, because the wrapper’s call operator is rvalue-qualified:

Does not compile
auto wrapper = capy::run_async(pool.get_executor());  // Don't do this
wrapper(compute());  // Error: operator() requires an rvalue

Calling std::move(wrapper)(compute()) compiles. It allocates from the right resource only if nothing changes the thread-local frame allocator in between. Creating or destroying another wrapper changes it, as does any co_await or task start. The compiler cannot catch that misuse.

Preconstructed task. Storing the task in a local and passing it in afterwards compiles and runs. Its frame is allocated by the time the wrapper exists, so it never sees the wrapper’s allocator. A moved-from local, or a task returned by an earlier statement, behaves the same way.

Wrapper function. A helper that accepts a task and performs the two-call pattern internally has the same effect. Its caller constructs the task as an argument to the helper, which is before the helper’s body runs.

The preconstructed-task and wrapper-function patterns produce no diagnostic at all: the task runs, on a coroutine frame that came from the wrong allocator. run_async_wrapper documents each pattern, and Frame Allocators carries the C++17-evaluation-order rationale.

Always use the two-call pattern in a single expression.

Completion Handler Overloads

run_async accepts optional completion handlers for results and exceptions:

// Result handler only (an unhandled exception calls std::terminate)
capy::run_async(ex, [](int result) {
    std::cout << "Got: " << result << "\n";
})(compute());

// Separate handlers for result and exception
capy::run_async(ex,
    [](int result) { std::cout << "Result: " << result << "\n"; },
    [](std::exception_ptr ep) {
        try { std::rethrow_exception(ep); }
        catch (std::exception const& e) {
            std::cout << "Error: " << e.what() << "\n";
        }
        // A non-std exception escaping here would call std::terminate
        catch (...) {
            std::cout << "Unknown error\n";
        }
    }
)(compute());

When no completion handler for the result is provided, the result is discarded. An exception that goes unhandled calls std::terminate. That happens when no completion handler for exceptions was supplied, or when a completion handler let one escape. To react to an error, pass a completion handler for exceptions. It receives the std::exception_ptr and should handle it in place rather than rethrowing. If the task is abandoned before it completes, as a context’s teardown does, no completion handler is called. To catch an error, co_await the work inside a coroutine and use try/catch rather than starting it fire-and-forget.

run: Executor Hopping Within Coroutines

Inside a coroutine, use run to execute a child task on a different executor:

capy::task<int> compute_on_pool(capy::thread_pool& pool)
{
    // This task runs on whatever executor we're already on

    // But this child task runs on the pool's executor:
    int result = co_await capy::run(pool.get_executor())(
        expensive_computation());

    // After co_await, we're back on our original executor
    co_return result;
}

Executor Affinity

By default, a task inherits its caller’s executor. This means completions are dispatched through that executor, ensuring thread affinity for thread-sensitive code.

A run overload that takes an executor overrides this inheritance for a specific child task, binding it to that executor. When it completes, the parent task resumes on its original executor.

This pattern is useful for:

  • Running CPU-intensive work on a thread pool

  • Performing I/O on an I/O-specific context

  • Ensuring UI updates happen on the UI thread

Stop Token Propagation

Both run_async and run propagate stop tokens to the task they start and all tasks it awaits. The task accesses its token via co_await this_coro::stop_token.

Injecting a Token with run_async

Since run_async is called from non-coroutine code, there is no caller token to inherit. Pass a stop token explicitly:

std::stop_source source;
capy::run_async(ex, source.get_token())(cancellable_task());

// Later, to request cancellation:
source.request_stop();

Inheritance with run

run is called from within a coroutine, so it inherits the caller’s stop token by default:

capy::task<void> parent()
{
    // Child automatically receives our stop token
    co_await capy::run(pool.get_executor())(child_task());
}

To override with a different token, pass it explicitly:

capy::task<void> parent()
{
    std::stop_source local;
    // Child gets local's token, not our caller's
    co_await capy::run(
        pool.get_executor(), local.get_token())(child_task());
}

Completion Handler Threading

Completion handlers passed to run_async are invoked on whatever thread the executor schedules:

// If pool has 4 threads, the handler runs on one of those threads
capy::run_async(pool.get_executor(), [](int result) {
    // This runs on a pool thread, NOT the main thread
    update_shared_state(result);
})(compute());