Bottom Up Coroutines in C++

A bottom-up tour of C++ coroutines: frames, promises, awaiters, symmetric transfer, future adapters, race conditions, testing, and benchmarks.

Bottom Up Coroutines in C++

The reason I made this guide is because coroutines in C++ are one of the hardest, if not the hardest, C++ concepts other than CRTP to understand. This blog post covers a bottom-up approach for coroutines, ranging from the initial use case in IO-bound work to their internals and how to design coroutines for specific purposes.

This was written while implementing coroutine support for Meta’s Dispenso, so some examples reference Dispenso types such as dispenso::Future<T> and dispenso::ThreadPool.

What are Coroutines

In essence, coroutines are program components that can pause execution and resume later while preserving their local state, supporting cooperative multitasking and asynchronous code.

They work concurrently, meaning multiple tasks can make progress over overlapping time periods without waiting for each other to finish completely before starting.

Analogy: when you stop reading, you place a bookmark on the exact page and line where you left off. You can then put the book down to do something else (like answer a phone call or read a different book) without losing your place or forgetting the story so far.

I am a visual learner, so here is a good diagram to visualize how coroutines work on a thread.

Coroutine and function execution on a thread

Figure 1 — A coroutine suspends and resumes on a thread without blocking it.

Think of coroutines as special functions that can pause, yield control, preserve state, and resume execution on a thread without blocking that thread.

In the image above, we can see how a coroutine and a function behave on a thread. Explaining further into the coroutine part, a coroutine has been created and called by the caller.

The coroutine creates a frame — a heap allocation during runtime — whose purpose is to store a coroutine’s execution state while the caller has control so it can resume later successfully.

Then the coroutine can give back control to the caller by suspending its execution. The keywords you want to look out for in C++ are co_await, co_yield, and co_return, which all suspend the coroutine’s execution and do something.

co_await, co_yield, and co_return

For co_await, that “something” is waiting for an asynchronous operation to finish. It checks if a task is ready and, if not, pauses the coroutine and hands its handle to the task so the task can wake the coroutine back up later.

For co_yield, that “something” is: hand a value to the caller. It saves a value into the coroutine’s promise object so the caller can read it right away, then pauses until the caller asks for the next value. We will talk more about what a promise object is and does later.

For co_return, that “something” is: finish the coroutine and clean up. It saves a final return value (if any), destroys all local variables inside the coroutine, and marks the coroutine as done.

Why do we use coroutines?

Let’s take a step back from systems programming and discuss where we could use it in high-throughput performant software.

Let’s say you have a web API or RPC service handling 20,000 concurrent users, and users spend most of their time waiting on database queries, Redis lookups, or downstream HTTP calls. Creating 20,000 OS threads would burn gigabytes of stack memory and thrash the CPU with context switches.

Each incoming request runs as a lightweight coroutine. Whenever it hits a network or DB call (await / co_await), it suspends and frees the thread to serve other ready requests.

In TypeScript, the premise of awaitable functions is created by using the async keyword alongside a return type of Promise<T>.

Defining a Coroutine in C++

Now that we discussed what we are making, how do we actually write it in C++? The first thing we want to define in our coroutine is a Task<T> or Task<> object: a wrapper class around a std::coroutine_handle<promise_type> that manages the coroutine’s lifecycle and suspension points, owns the frame, and owns the return value.

The snippets in this post are intentionally compact. Accessors such as operator bool() and promise() are omitted, and some helper members are assumed. The focus is on the coroutine protocol and the design decisions behind it.

What should Task<T> be able to do?

  • It should own and manage the coroutine lifetime (RAII).
  • Support lazy execution: a Task<T> shouldn’t run when called or instantiated; it should only start when co_awaited.
  • Support void completion by specializing promise_type with return_void().
  • Handle exception propagation by capturing exceptions in promise_type::unhandled_exception() via std::current_exception() and rethrowing them in await_resume() with std::rethrow_exception().
  • In various cases, support symmetric transfer (later).
  • Provide an awaitable adapter or method that resumes the task on a specific executor or thread pool before continuing.
  • Enforce safe value categories.

Now we can define a basic Task<T> that owns the coroutine handle. Don’t worry about how the promise types are handled just yet!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
template <typename T = void>
class Task {
public:
    using promise_type = detail::TaskPromise<T>;
    using value_type = T;

    Task(const Task&) = delete;
    Task& operator=(const Task&) = delete;

    Task(Task&& other) noexcept
        : handle_(std::exchange(other.handle_, {})) {}

    Task& operator=(Task&& other) noexcept {
        if (this != &other) {
            if (handle_) {
                handle_.destroy();
            }

            handle_ = std::exchange(other.handle_, {});
        }

        return *this;
    }

    ~Task() {
        if (handle_) {
            handle_.destroy();
        }
    }

private:
    explicit Task(
        std::coroutine_handle<promise_type> handle
    ) noexcept
        : handle_(handle) {}

    std::coroutine_handle<promise_type> handle_{};

    friend struct detail::TaskPromise<T>;
};

Why is Task<T> move-only?

Task<T> is move-only because a coroutine handle represents ownership of a coroutine frame. If multiple Task objects owned the same handle, they could independently attempt to destroy the same frame. This would result in undefined behavior.

To avoid this, we delete the copy constructor and copy assignment operator and implement move semantics.

1
2
Task(Task&& other) noexcept
    : handle_(std::exchange(other.handle_, {})) {}

std::exchange transfers the handle from the source object and replaces it with an empty handle. This ensures that only one Task owns the coroutine frame at a time.

Why destroy the coroutine frame in the destructor?

1
2
3
4
5
~Task() {
    if (handle_) {
        handle_.destroy();
    }
}

The coroutine frame is dynamically managed by the coroutine internals. It contains the coroutine’s local variables, promise object, and other state required to resume execution. Destroying the handle destroys the coroutine frame and releases its associated resources.

Making the Task Lazy

One of the defining characteristics of our task is lazy execution. We don’t want the coroutine body to execute immediately when the coroutine function is called. The coroutine body should only execute once the task is awaited. We achieve this through the promise type’s initial_suspend() function:

1
2
3
4
5
struct TaskPromiseBase {
    std::suspend_always initial_suspend() noexcept {
        return {};
    }
};

std::suspend_always is a C++20 awaitable type defined in <coroutine> that tells a coroutine to always suspend at a suspension point.

Execution can then be initiated when another coroutine awaits the task.

Defining the promise type

The promise type is what Task<T> uses to control how a coroutine starts, suspends, yields values, returns results, and handles exceptions inside the coroutine state.

For a value-returning task, we can start with:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
template <typename T>
struct TaskPromise : TaskPromiseBase {
    static_assert(
        !std::is_reference_v<T>,
        "Task<T&> is not supported"
    );

    Task<T> get_return_object() noexcept;

    void return_value(T value) {
        value_.emplace(std::move(value));
    }

private:
    std::optional<T> value_{};
};

get_return_object()

The compiler calls get_return_object() when creating the coroutine. We use std::coroutine_handle::from_promise() to obtain a handle referring to the coroutine associated with this promise, then wrap that handle inside our Task<T>.

This establishes the ownership relationship between the task and the coroutine frame.

1
2
3
4
5
Task<T> get_return_object() noexcept {
    return Task<T>{
        std::coroutine_handle<TaskPromise<T>>::from_promise(*this)
    };
}

Storing the return value

1
2
3
void return_value(T value) {
    value_.emplace(std::move(value));
}

Here we use std::optional because the result does not necessarily exist when the coroutine is first created, and optional allows us to represent both states.

Supporting Task<void>

Not every coroutine needs to return a value. The promise interface for a value-returning coroutine uses return_value(). However, a coroutine returning void requires return_void(), so we provide a specialization.

1
2
3
4
5
6
template <>
struct TaskPromise<void> : TaskPromiseBase {
    Task<void> get_return_object() noexcept;

    void return_void() noexcept {}
};

The distinction is important because a promise type cannot provide both return_value() and return_void(). This specialization allows us to support both.

Exception propagation

Coroutines need a mechanism for capturing exceptions thrown during execution. The compiler invokes unhandled_exception() whenever an exception escapes the coroutine body. We can implement this in our common promise base.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
struct TaskPromiseBase {
    std::exception_ptr exception_{};

    void unhandled_exception() noexcept {
        exception_ = std::current_exception();
    }

    void rethrowIfFailed() {
        if (exception_) {
            std::rethrow_exception(exception_);
        }
    }

    std::suspend_always initial_suspend() noexcept {
        return {};
    }
};

Instead of allowing an exception to escape the coroutine frame, we capture it using std::current_exception().

Awaiting a Task

Now we need to make our Task<T> awaitable. What does that mean? Awaitable means allowing other coroutines to use the co_await operator on an instance of your Task<T>.

To make Task<T> awaitable, you must provide an awaiter. The compiler uses three functions when processing a co_await expression: await_ready(), await_suspend(), and await_resume().

We can implement these through a separate awaiter type.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
template <typename T>
struct TaskAwaiter {
    explicit TaskAwaiter(Task<T>&& task) noexcept
        : task_(std::move(task)) {}

    bool await_ready() const noexcept {
        return !task_ || task_.handle_.done();
    }

    std::coroutine_handle<> await_suspend(
        std::coroutine_handle<> continuation
    ) noexcept {
        task_.handle_.promise().continuation(continuation);
        return task_.handle_;
    }

    T await_resume() {
        task_.handle_.promise().rethrowIfFailed();

        return task_.handle_.promise().value();
    }

private:
    Task<T> task_;
};

await_ready()

This determines whether the awaiting coroutine needs to suspend. If the task is already completed, we don’t need to suspend. Otherwise, execution proceeds to await_suspend(). The empty-task case is also handled here; await_resume() is responsible for reporting an invalid moved-from task.

1
2
3
bool await_ready() const noexcept {
    return !task_ || task_.handle_.done();
}

await_suspend()

1
2
3
4
5
6
7
std::coroutine_handle<> await_suspend(
    std::coroutine_handle<> continuation
) noexcept {
    task_.handle_.promise().continuation(continuation);

    return task_.handle_;
}

When a coroutine awaits another coroutine, the compiler passes the awaiting coroutine’s handle into await_suspend(). We then store that handle inside the child coroutine’s promise. This handle represents the continuation: the coroutine that should resume after the child completes.

We then return the child’s coroutine handle.

Returning a coroutine handle from await_suspend() enables symmetric transfer. Instead of manually calling resume(), we tell the coroutine machinery which coroutine should execute next. This gives us a clean way to transfer execution from the parent coroutine to the child.

await_resume()

1
2
3
4
5
T await_resume() {
    task_.handle_.promise().rethrowIfFailed();

    return task_.handle_.promise().value();
}

Once the child coroutine completes, execution returns to the awaiting coroutine. We need to check if the child encountered an exception. If an exception was captured, we rethrow it. Otherwise, we retrieve the stored result.

The awaiter owns the task, so when the await expression finishes and the awaiter is destroyed, the task’s coroutine frame is also destroyed.

Symmetric Transfer

Symmetric transfer is a mechanism where one coroutine suspends and directly resumes another coroutine without building up nested call-stack frames.

We need to define what happens when a coroutine completes. For this, we implement a custom final awaiter.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
struct final_awaitable {
    bool await_ready() const noexcept {
        return false;
    }

    template <typename Promise>
    std::coroutine_handle<> await_suspend(
        std::coroutine_handle<Promise> handle
    ) noexcept {
        if (handle.promise().continuation_) {
            return handle.promise().continuation_;
        }

        return std::noop_coroutine();
    }

    void await_resume() const noexcept {}
};

And inside our promise:

1
2
3
final_awaitable final_suspend() noexcept {
    return {};
}

A continuation is simply the calling coroutine that is waiting for the current coroutine to finish.

When the coroutine reaches its final suspension point, the final awaiter is invoked. If a continuation exists, we return its handle.

Otherwise, we return std::noop_coroutine(). If a coroutine finishes and discovers there is no next coroutine to resume, await_suspend still needs to return a valid, non-null handle.

Implementing with dispenso::Future<T>

So far, we’ve built our own Task<T> abstraction to control where a coroutine resumes execution. However, not every asynchronous operation in a C++ application is implemented using coroutines.

Many existing asynchronous APIs use futures to represent the eventual result of an operation. In this section, we’ll adapt Dispenso’s dispenso::Future<T> to the C++ coroutine protocol.

For example, a future represents a value that may not be available yet but will become available at some point in the future.

We want to be able to write something like this:

1
2
3
4
5
6
7
Task<int> calculate() {
    dispenso::Future<int> future = start_async_operation();

    int result = co_await future;

    co_return result;
}

Rather than blocking a thread while waiting for the future to become ready, we want to suspend the coroutine and resume it once the future completes. This requires us to adapt the future interface to the C++ coroutine protocol.

We need an awaiter

Recall that the compiler expects an awaitable object to provide three operations: await_ready(), await_suspend(), and await_resume().

Our future already represents an asynchronous operation, but it does not necessarily implement this coroutine interface. We can solve this by introducing an adapter:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
template <typename T>
struct FutureAwaiter {
    explicit FutureAwaiter(dispenso::Future<T> future)
        : future_(std::move(future)) {}

    bool await_ready() const {
        return future_.is_ready();
    }

    std::coroutine_handle<> await_suspend(
        std::coroutine_handle<> handle
    );

    T await_resume();

private:
    dispenso::Future<T> future_;
};

The awaiter owns a dispenso::Future<T> and is responsible for coordinating the future’s completion with the suspended coroutine.

Checking whether the future is ready

The first thing we want to determine is whether the asynchronous operation has already completed. If the future is ready, there is no reason to suspend the coroutine. The compiler can immediately proceed to await_resume().

Otherwise, we need to arrange for the coroutine to resume when the future becomes ready.

Resuming the coroutine when the future completes

This is one of the trickier parts of the implementation.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
std::coroutine_handle<> await_suspend(
    std::coroutine_handle<> handle
) {
    handle_ = handle;

    future_.then(
        [this](Future<T>&&) {
            auto previous = status_.exchange(
                kCallbackDone,
                std::memory_order_acq_rel
            );

            if (previous == kSuspended) {
                handle_.resume();
            }
        },
        kImmediateInvoker
    );

    if (status_.exchange(
            kSuspended,
            std::memory_order_acq_rel
        ) == kCallbackDone) {
        return handle_;
    }

    return std::noop_coroutine();
}

Let’s break down what’s happening in the snippet above. First, we store the coroutine handle:

1
handle_ = handle;

This handle represents the coroutine that is currently awaiting the future. We then register a continuation using:

1
future_.then(callback, kImmediateInvoker);

The callback is invoked when the future becomes ready. When that happens, we want to resume the suspended coroutine. At first glance, this seems straightforward:

1
2
3
4
5
future_.then(
    [handle] {
        handle.resume();
    }
);

However, there is a concurrency problem.

The race condition between suspension and completion

A race condition occurs when two or more threads access shared state and try to change it at the same time.

Consider what happens when the future completes immediately after we register the callback.

Here there are two operations that can race: (a) the coroutine transitions into its suspended state, and (b) the future completes and invokes its callback.

A callback is a function you pass into another piece of code so it can run later; in this case, this is what a future requires.

This races because the future can complete on another thread before the coroutine finishes saving its state and marking itself as suspended.

Here is a visualization.

Race condition between coroutine suspension and future completion

Figure 2 — The future callback and await_suspend() can run concurrently.

We must ensure that the coroutine is resumed exactly once. To solve this, we introduce an atomic state variable.

1
2
3
4
5
6
7
enum Status : int {
    kSuspending,
    kSuspended,
    kCallbackDone
};

std::atomic<int> status_{kSuspending};

kSuspending: the coroutine is registering its callback and transitioning toward suspension. kSuspended: the coroutine has committed to suspension. kCallbackDone: the future’s completion callback has executed.

The important detail is that the callback and await_suspend() coordinate through atomic exchanges.

Understanding the atomic exchange

1
2
3
4
5
6
7
8
auto previous = status_.exchange(
    kCallbackDone,
    std::memory_order_acq_rel
);

if (previous == kSuspended) {
    handle_.resume();
}

The callback changes the state to kCallbackDone. It then examines the previous state. If the previous state was kSuspended, the coroutine has already committed to suspension. Therefore, the callback can safely resume it.

If the previous state was kSuspending, the coroutine has not yet committed to suspension. In that case, the callback does not resume the coroutine.

Instead, it leaves the state as kCallbackDone, allowing await_suspend() to detect that completion has already occurred. After registering the callback, await_suspend() executes:

1
2
3
4
5
6
7
8
if (status_.exchange(
        kSuspended,
        std::memory_order_acq_rel
    ) == kCallbackDone) {
    return handle_;
}

return std::noop_coroutine();

There are now two possible execution paths here.

Case 1: The callback completes first

The callback changes the state from kSuspending to kCallbackDone. When await_suspend() performs its exchange, it observes kCallbackDone. This uses symmetric transfer to continue execution without requiring the callback to resume the coroutine.

Case 2: The coroutine commits to suspension first

await_suspend() changes the state from kSuspending to kSuspended. It returns std::noop_coroutine(). Later, when the future completes, the callback observes that the previous state was kSuspended and resumes the coroutine.

This coordination ensures that the coroutine is resumed exactly once, regardless of which operation wins the race.

Retrieving the result

Once the coroutine resumes, the compiler invokes await_resume().

1
2
3
4
5
6
7
8
9
10
11
12
T await_resume() {
    if constexpr (std::is_void_v<T>) {
        future_.get();
    } else if constexpr (
        std::is_reference_v<T> ||
        std::is_copy_constructible_v<T>
    ) {
        return future_.get();
    } else {
        return future_.take();
    }
}

The implementation handles different result categories. For void, there is no result to return. We simply call get() to retrieve completion and propagate any stored exception.

For copy-constructible types, we use get(). For non-copyable types, we use take() to transfer the result out of the future.

This allows the awaiter to support both copyable and move-only result types.

1
2
3
dispenso::Future<int> integer_future;
dispenso::Future<std::unique_ptr<int>> pointer_future;
dispenso::Future<void> void_future;

Making dispenso::Future<T> directly awaitable

We now have an awaiter, but we still need a way for the compiler to discover it when encountering co_await.

We can accomplish this by overloading operator co_await.

For lvalue futures:

1
2
3
4
template <typename T>
auto operator co_await(dispenso::Future<T>& future) {
    return detail::FutureAwaiter<T>{future};
}

For rvalue futures:

1
2
3
4
5
6
template <typename T>
auto operator co_await(dispenso::Future<T>&& future) {
    return detail::FutureAwaiter<T>{
        std::move(future)
    };
}

Providing both overloads allows us to await either an existing future or a temporary future.

The awaiter takes ownership of its own future object. For the lvalue overload, this means the dispenso::Future<T> must be copyable. For the rvalue overload, ownership is transferred through move construction.

Writing Tests using GoogleTest and Sanitizers

Implementing our coroutine abstraction is only half the work. We also need to verify that its lifecycle, execution, and result handling behave as expected.

We’ll use GoogleTest (GTest) to write a few fundamental tests for our Task<T> implementation.

Let’s define a simple coroutine:

1
2
3
4
Task<int> countRuns(int& runs) {
    ++runs;
    co_return 42;
}

We can verify lazy execution with:

1
2
3
4
5
6
7
8
9
10
11
TEST(Task, LazyStart) {
    int runs = 0;

    Task<int> task = countRuns(runs);

    EXPECT_EQ(runs, 0);

    EXPECT_EQ(dispenso::sync_wait(std::move(task)), 42);

    EXPECT_EQ(runs, 1);
}

Testing Move Semantics

1
2
3
4
5
6
7
8
9
10
TEST(Task, Move) {
    int runs = 0;

    Task<int> first = countRuns(runs);

    Task<int> second = std::move(first);

    EXPECT_FALSE(static_cast<bool>(first));
    EXPECT_TRUE(static_cast<bool>(second));
}

Testing exception propagation

Exceptions thrown inside a coroutine should be captured by promise_type::unhandled_exception() and rethrown when the result is awaited.

1
2
3
4
Task<int> throwingValue() {
    throw std::runtime_error("value boom");
    co_return 0;
}

We can test this using:

1
2
3
4
5
6
TEST(Task, ExceptionPropagation) {
    EXPECT_THROW(
        dispenso::sync_wait(throwingValue()),
        std::runtime_error
    );
}

Testing nested coroutines

One of the benefits of coroutines is that we can compose asynchronous operations using co_await.

Let’s define a small chain of nested tasks:

1
2
3
4
5
6
7
8
9
10
Task<int> answer(int v) {
    co_return v;
}

Task<int> threeDeep(int v) {
    const int a = co_await answer(v);
    const int b = co_await answer(a + 1);

    co_return co_await answer(b + 1);
}

And test the result:

1
2
3
4
5
6
TEST(Task, NestedAwait) {
    EXPECT_EQ(
        dispenso::sync_wait(threeDeep(10)),
        12
    );
}

Testing with Sanitizers

While unit tests verify the expected behavior of our coroutine implementation, they don’t necessarily catch memory errors, undefined behavior, or data races.

AddressSanitizer (ASan): detects memory errors such as use-after-free and out-of-bounds accesses. UndefinedBehaviorSanitizer (UBSan): detects various forms of undefined behavior. ThreadSanitizer (TSan): detects data races and synchronization issues.

This is particularly useful when testing coroutine implementations because coroutine frames can outlive their original calling scope, and continuations may resume on different threads.

For example, ThreadSanitizer can help identify synchronization issues in our FutureAwaiter<T> implementation, while AddressSanitizer can help detect coroutine frame lifetime errors.

These configurations are also exercised in the project’s CI pipeline, including ThreadSanitizer tests under Clang.

Sanitizers complement our unit tests by helping identify problems that ordinary assertions may not reveal.

Testing was particularly important when integrating futures with coroutines. It was through testing that I discovered the race conditions introduced by combining asynchronous future completion with coroutine suspension.

Benchmarking and Profiling

After implementing our coroutine abstraction, I wanted to understand how it compared to Dispenso’s existing dispenso::Future<T> implementation.

I ran a series of benchmarks on macOS (ARM64, 10-core), comparing coroutine-based tasks against futures across different asynchronous execution patterns.

PatternTask<T>dispenso::FutureFaster
Sync chain (depth 1)30.3 ns8.42 nsdispenso::Future 3.6x
Sync chain (depth 8)154 ns3,740 nsTask 24.3x
Sync chain (depth 32)570 ns15,908 nsTask 27.9x
Pool dispatch (1 task)4,259 ns173 nsdispenso::Future 24.6x
Pool chain (4 hops)246,207 ns1,372 nsdispenso::Future 179x
Pool chain (16 hops)132,192 ns5,775 nsdispenso::Future 22.9x
Fan-out/fan-in (8 tasks)21,918 ns11,614 nsdispenso::Future 1.9x
Fan-out/fan-in (32 tasks)25,770 ns42,821 nsTask 1.7x
Pending future8,180 ns2,101 nsdispenso::Future 3.9x

Understanding the results

Coroutines perform particularly well as the chain gets deeper. At depth 1, dispenso::Future is faster, but at depths 8 and 32, Task<T> becomes significantly faster.

One possible explanation is that dispenso::Future::then creates and links continuations for each operation, whereas coroutine execution uses coroutine frames and symmetric transfer between tasks.

Thread-pool dispatch and chaining

Interestingly, dispenso::Future performs considerably better in these benchmarks. The dispenso::Future implementation is particularly efficient for the tested async and then scheduling patterns.

Our coroutine implementation introduces additional overhead through sync_wait, coroutine frame management, and schedule_on.

Fan-out/fan-in

The results are much closer here.

Both implementations use Dispenso (the project where I implemented these coroutines) futures underneath to execute asynchronous work. The coroutine and future wrappers have different overheads, and the winner changes depending on the number of tasks.

Awaiting a pending future

Directly calling dispenso::Future::get() is faster than awaiting the future through Task<T> in this benchmark.

This is expected to be an important consideration when deciding whether an operation should use a coroutine abstraction or a direct future-based interface.

Profiling Task<T>: Pool-chain flamegraph

Flamegraph for the Dispenso coroutine pool chain benchmark

Figure 3 — Flamegraph for dispensoCoroPoolChain.

The flamegraph for dispensoCoroPoolChain shows that a significant portion of execution time is spent in scheduling and synchronization rather than computation itself.

The main hot areas include dispensoCoroPoolChain(.resume), sync_wait and syncWaitEntry, ThreadPool::forceEnqueue, and PoolWakeState::claimAndWakeOne.

We also see time spent in the kernel’s __ulock_* wait/wake operations, indicating overhead associated with putting threads to sleep and waking them up.

This suggests that repeatedly scheduling coroutine continuations through the global thread pool introduces considerable overhead, particularly for workloads consisting of many small sequential operations.

This motivates exploring interleaved batching, where multiple coroutine streams can execute within the same batch, reducing reliance on global scheduling and using symmetric transfer to switch between streams. We will discuss this in the next section.

Benchmark conclusion

The benchmark results reinforce that both abstractions have their place, and choosing between them should depend on the workload rather than assuming one is inherently faster.

This also sets the stage for the next part of the series, where we’ll explore how coroutines can achieve much better performance in compute-bound workloads, particularly when we move beyond simple scheduling and focus on efficiently composing and executing computational work.

Writing compute-bound coroutines

While our benchmarks show that coroutines can be efficient for composing asynchronous operations, there is another opportunity for performance improvement, particularly in compute-heavy and memory-bound workloads.

In the next blog, we’ll explore interleaved batching, adapting the group-interleaving approach from VLDB.

The idea is to keep multiple independent coroutine streams in flight within the same batch. When one coroutine encounters a long-latency memory dependency or issues an explicit prefetch, execution transfers to another coroutine rather than yielding back to the global thread-pool scheduler.

We’ll explore two execution policies:

  • dispenso::parallel_policy: designed for compute-heavy workloads, executing large, contiguous batches with minimal scheduling overhead to improve task affinity, instruction-level parallelism, cache locality, and SIMD utilization.
  • dispenso::interleave_policy: designed for latency-bound workloads, maintaining multiple independent coroutine streams in flight and using explicit interleaving points to transfer execution through symmetric transfer.

The goal is to better utilize available CPU resources by adapting coroutine execution to the characteristics of the workload.

Rather than treating every coroutine as an independently scheduled task, we can execute groups of coroutines together and use interleaving to hide memory latency.

Future Coroutine Work

The next phase of development will focus on introducing parallelism combinators, starting with spawn_on(ThreadPool&, Task<T>) to execute tasks on specific thread pools, followed by variadic and vector-based implementations of when_all to coordinate multiple tasks, with when_any as a potential addition.

After that, I plan to introduce an asynchronous I/O infrastructure through an IoContext abstraction, supporting platform-specific backends including Linux io_uring, Linux epoll as a fallback, macOS kqueue, and Windows IOCP. This will provide the foundation for asynchronous file operations such as read_file and write_file.

Ultimately, the goal is to evolve the coroutine library beyond basic asynchronous task composition into a flexible, cross-platform execution framework that supports parallel workloads, asynchronous I/O, and efficient compute-bound execution.

References

This post is licensed under CC BY 4.0 by the author.

Trending Tags