Modern Asynchronous Programming in C++20 with Coroutines: Build Task, Generator, and Awaitable Types from Scratch

Programming tutorial - IT technology blog
Programming tutorial - IT technology blog

Suppose your C++ backend needs to fetch a user profile from PostgreSQL, call a billing API, and stream paginated invoices to the client. Blocking calls park an entire OS thread on every network wait. Nested callbacks avoid the thread cost, but they scatter simple business logic across lambdas and manual pointer lifetimes.

C++20 coroutines break that deadlock. They let a function pause mid-execution, release its thread for other work, and resume right where it stopped—with local variables intact.

The Real-World Problem: Blocking Threads vs. Callback Spaghetti

When you first write I/O-bound C++—reading sockets, querying databases, or waiting on timers—spawning one thread per task feels natural. That works fine for 10 users. At 10,000 concurrent connections, it falls apart. On Linux, each thread reserves 8 MB of virtual stack space by default, meaning 10,000 threads claim 80 GB of address space while the kernel burns CPU cycles on context switches.

Asynchronous callbacks were the classic workaround: start an operation, pass a completion lambda, and return immediately. You save threads, yet you lose structured control flow. Try writing a retry loop with try/catch across three chained HTTP calls, and the code quickly turns into callback spaghetti.

Root Cause Analysis: Why Traditional C++ Functions Cannot Pause

Regular C++ functions are chained to the call stack. Call a function, and its local variables live in a stack frame. Return from it, and that frame is popped and destroyed. There is no built-in way to pause on line 12, wait for a socket, and resume later.

Without mid-function suspension, C++ developers only had two options:

  • Keep the thread blocked so the call stack stays intact while waiting.
  • Destroy the stack frame and move every local variable into a heap-allocated struct or lambda capture, splitting one workflow into fragmented callbacks.

Stackless coroutines in C++20 offer a third path. Whenever a function contains co_await, co_yield, or co_return, the compiler rewrites it into a state machine. Local variables and the resume point move into a compiler-managed coroutine frame, freeing the OS thread during every pause.

Solutions Compared: Threads, Callbacks, and C++20 Coroutines

Here is how the three approaches stack up for concurrent or lazy C++ workflows:

  • OS Threads + Blocking I/O: Clean sequential code and easy debugging, but heavy memory and scheduling overhead at scale (thousands of threads).
  • Callbacks / Futures: Non-blocking and fast, yet painful to compose when you need loops, error handling, or cancellation across multiple async steps.
  • C++20 Coroutines: Sequential top-to-bottom syntax via co_await and co_yield with non-blocking efficiency. The catch? C++20 only ships low-level primitives in <coroutine>—no built-in Task (and std::generator did not arrive until C++23).

Writing Generator, Awaitable, and Task from scratch demystifies those primitives. Once you see how the compiler wires them together, libraries like cppcoro and Boost.Asio make immediate sense.

Building Generator, Awaitable, and Task Step by Step

Step 1: Enable C++20 in Your Compiler

You need GCC 10+, Clang 14+, or MSVC 19.28+ with C++20 mode enabled. On Linux with GCC or Clang, compile with -std=c++20:

g++ -std=c++20 -Wall -Wextra -O2 main.cpp -o coro_demo
./coro_demo

Step 2: Build a Lazy Generator<T> with co_yield

A Generator<T> produces values one at a time on demand. Every C++20 coroutine return type must define a nested promise_type. The compiler calls hooks on promise_type when the coroutine starts, yields a value, throws, or finishes.

#include <coroutine>
#include <exception>
#include <iostream>
#include <utility>

template <typename T>
struct Generator {
    struct promise_type {
        T current_value{};

        Generator get_return_object() {
            return Generator{std::coroutine_handle<promise_type>::from_promise(*this)};
        }
        // Suspend immediately so the caller pulls values lazily
        std::suspend_always initial_suspend() noexcept { return {}; }
        // Keep frame alive at the end so destructor can destroy it safely
        std::suspend_always final_suspend() noexcept { return {}; }

        std::suspend_always yield_value(T value) noexcept {
            current_value = std::move(value);
            return {};
        }
        void return_void() noexcept {}
        void unhandled_exception() { std::terminate(); }
    };

    std::coroutine_handle<promise_type> handle;

    explicit Generator(std::coroutine_handle<promise_type> h) : handle(h) {}
    Generator(const Generator&) = delete;
    Generator& operator=(const Generator&) = delete;

    Generator(Generator&& other) noexcept : handle(other.handle) {
        other.handle = nullptr;
    }
    ~Generator() {
        if (handle) handle.destroy();
    }

    bool next() {
        if (!handle || handle.done()) return false;
        handle.resume();
        return !handle.done();
    }

    T value() const { return handle.promise().current_value; }
};

Generator<int> count_up(int max) {
    for (int i = 1; i <= max; ++i) {
        co_yield i;
    }
}

Two details matter here: Generator is move-only, and its destructor calls handle.destroy(). Because final_suspend() returns std::suspend_always, the coroutine frame stays alive until Generator leaves scope, preventing use-after-free bugs.

Step 3: Build a Custom Awaitable Type

Writing co_await expr; tells the compiler to treat expr as an Awaitable with three methods:

  1. await_ready(): Returns true if the result is already available, or false to suspend.
  2. await_suspend(std::coroutine_handle<>): Runs right after suspension, receiving the paused coroutine’s handle so an event loop or timer can resume it later.
  3. await_resume(): Runs upon wakeup and returns the result of the co_await expression.
struct StepAwaitable {
    int value_to_return;

    bool await_ready() const noexcept {
        return false; // Force suspension so we can see it in action
    }

    void await_suspend(std::coroutine_handle<> handle) const noexcept {
        std::cout << "[Awaitable] Coroutine suspended, resuming immediately...\n";
        handle.resume();
    }

    int await_resume() const noexcept {
        return value_to_return;
    }
};

Production I/O frameworks do not call handle.resume() inline like this demo. Instead, await_suspend registers handle with an event loop—such as epoll on Linux or io_uring—and resumes it only when the socket or timer fires.

Step 4: Build a Task<T> Type for co_await and co_return

Unlike Generator, which yields a stream synchronously, Task<T> models an async operation that produces a single result via co_return. Better yet, one Task<T> can co_await another.

#include <optional>

template <typename T>
struct Task {
    struct promise_type {
        std::optional<T> result;
        std::coroutine_handle<> continuation{nullptr};

        struct FinalAwaiter {
            bool await_ready() noexcept { return false; }
            std::coroutine_handle<> await_suspend(
                std::coroutine_handle<promise_type> h) noexcept {
                auto cont = h.promise().continuation;
                return cont ? cont : std::noop_coroutine();
            }
            void await_resume() noexcept {}
        };

        Task get_return_object() {
            return Task{std::coroutine_handle<promise_type>::from_promise(*this)};
        }
        std::suspend_always initial_suspend() noexcept { return {}; }
        FinalAwaiter final_suspend() noexcept { return {}; }

        void return_value(T val) noexcept { result = std::move(val); }
        void unhandled_exception() { std::terminate(); }
    };

    std::coroutine_handle<promise_type> handle;

    explicit Task(std::coroutine_handle<promise_type> h) : handle(h) {}
    Task(const Task&) = delete;
    Task(Task&& other) noexcept : handle(other.handle) { other.handle = nullptr; }
    ~Task() {
        if (handle) handle.destroy();
    }

    // Make Task<T> itself awaitable
    bool await_ready() const noexcept { return false; }
    std::coroutine_handle<> await_suspend(std::coroutine_handle<> awaiting) noexcept {
        handle.promise().continuation = awaiting;
        return handle; // Symmetric transfer to the child task
    }
    T await_resume() { return std::move(*handle.promise().result); }

    T run_sync() {
        handle.resume();
        return std::move(*handle.promise().result);
    }
};

Notice FinalAwaiter in the code above. Returning the waiting coroutine’s handle from await_suspend triggers symmetric transfer, which avoids stack overflow even if you chain 10,000 nested tasks. Here are all three components running together in main():

Task<int> fetch_user_score() {
    int base = co_await StepAwaitable{40};
    co_return base + 2;
}

Task<int> compute_bonus() {
    int score = co_await fetch_user_score();
    co_return score * 2;
}

int main() {
    auto gen = count_up(3);
    while (gen.next()) {
        std::cout << "Generated: " << gen.value() << "\n";
    }

    auto task = compute_bonus();
    std::cout << "Task result: " << task.run_sync() << "\n";
    return 0;
}

Practical Tips Before You Ship

  • Pass parameters by value: If a coroutine accepts a const std::string& and suspends, the caller’s temporary string can vanish before resumption. Pass by value unless you guarantee the caller outlives the coroutine.
  • Wrap handles in RAII: Never leave a raw std::coroutine_handle unmanaged. Wrap it in a move-only type that calls destroy() in its destructor.
  • Run Sanitizers early: Compile with -fsanitize=address,undefined in CI to catch dangling coroutine frames before they reach production.

With promise_type, std::coroutine_handle, and the three awaitable hooks under your belt, C++20 coroutines stop looking like compiler magic. They become a predictable tool for writing fast, readable async services.

Share: