Site Tools


wiki:hpp-coroutine

Table of Contents

<coroutine>

<coroutine> provides the low-level coroutine machinery (promise types, coroutine handles, awaiters) for implementing stackless coroutines in C++20. Coroutines can suspend and resume without threads, enabling async I/O and lazy generators.

The header itself is foundational; you typically use higher-level abstractions like std::generator or async frameworks built on top of it. Writing a coroutine type requires careful handling of promise and awaiter contracts.

Example

This example defines a simple generator coroutine that yields three integers sequentially, demonstrating suspension and resumption without threads.

// compile: g++ -std=c++20 -o coroutineexample coroutineexample.cpp
// run: ./coroutineexample
// description: simple generator coroutine
 
#include <coroutine>
#include <iostream>
 
template <typename T>
struct Generator {
    struct promise_type {
        T current;
        auto get_return_object() {
            return Generator{std::coroutine_handle<promise_type>::from_promise(*this)};
        }
        auto initial_suspend() { return std::suspend_never{}; }
        auto final_suspend() noexcept { return std::suspend_always{}; }
        void unhandled_exception() {}
        void return_void() {}
        auto yield_value(T val) {
            current = val;
            return std::suspend_always{};
        }
    };
 
    std::coroutine_handle<promise_type> handle;
 
    bool next() {
        if (handle.done()) return false;
        handle.resume();
        return !handle.done();
    }
    T value() { return handle.promise().current; }
};
 
Generator<int> count_to_three() {
    co_yield 1;
    co_yield 2;
    co_yield 3;
}
 
int main() {
    auto gen = count_to_three();
    while (gen.next()) {
        std::cout << gen.value() << "\n";
    }
    return 0;
}
wiki/hpp-coroutine.md · Last modified: by 127.0.0.1