C++ · Module 17 · Lesson 81 min read

Coroutines & Generators

What is a coroutine?

A function that can suspend its execution and resume later, keeping its local variables. A function becomes a coroutine if it uses:

KeywordMeaning
co_yield valueproduce a value and pause
co_await exprpause until something is ready
co_return valuefinish

Generators with std::generator (C++23, <generator>) ✅

CSS
std::generator<int> count_up(int n) {
    for (int i = 1; i <= n; ++i) co_yield i;
}
for (int x : count_up(5)) ...
  • Values are produced lazily, one per iteration
  • Infinite sequences are fine: the generator only runs as far as you consume it
  • Works with ranges: count_up(100) | std::views::take(3)

Why generators?

  • Stream large data (lines of a huge file) without loading it all
  • Express sequences naturally (Fibonacci, IDs, paginated API results, date ranges)
  • Cleaner than writing an iterator class by hand

Asynchronous coroutines (co_await)

The other big use: async I/O — a network request suspends the coroutine instead of blocking a thread, and resumes when data arrives. C++20 provides only the low-level machinery (promise types, awaitables, std::coroutine_handle); libraries such as Asio, cppcoro, libcoro or Qt provide ready-made task types.

How it works (simplified)

  • The compiler turns the coroutine into a state machine
  • Its local variables live in a coroutine frame (usually on the heap)
  • The return type (e.g. std::generator<int>) controls behaviour via its promise_type

Cautions ⚠️

  • Don't take parameters by reference if the coroutine outlives the caller's objects (the frame keeps the reference, not the object)
  • Writing your own coroutine types is advanced — prefer library types

Running this example

std::generator is C++23: compile with -std=c++23 (GCC 14+, MSVC 2022 17.x).

Example

C++
#include <generator>
#include <iostream>
#include <ranges>
#include <string>
#include <vector>

std::generator<long long> fibonacci() {               // infinite, but lazy
    long long a = 0, b = 1;
    while (true) {
        co_yield a;
        auto next = a + b;
        a = b;
        b = next;
    }
}

std::generator<std::string> receipt_ids(std::string prefix, int start, int count) {   // by value: safe
    for (int i = 0; i < count; ++i) co_yield prefix + "-" + std::to_string(start + i);
}

std::generator<double> monthly_savings(double deposit, double rate, int months) {
    double balance = 0;
    for (int m = 1; m <= months; ++m) {
        balance = balance * (1 + rate) + deposit;
        co_yield balance;
    }
}

std::generator<std::vector<int>> pages(const std::vector<int>& items, std::size_t page_size) {
    for (std::size_t i = 0; i < items.size(); i += page_size)
        co_yield std::vector<int>(items.begin() + static_cast<long>(i),
                                  items.begin() + static_cast<long>(std::min(items.size(), i + page_size)));
}

int main() {
    std::cout << "first 10 Fibonacci numbers:";
    for (long long f : fibonacci() | std::views::take(10)) std::cout << ' ' << f;
    std::cout << '\n';

    std::cout << "first Fibonacci number above 1000: ";
    for (long long f : fibonacci())
        if (f > 1000) { std::cout << f << '\n'; break; }

    for (const auto& id : receipt_ids("RCPT", 2026, 3)) std::cout << id << ' ';
    std::cout << '\n';

    int m = 0;
    for (double b : monthly_savings(5000, 0.01, 6)) std::cout << "month " << ++m << ": " << static_cast<long>(b) << '\n';

    std::vector<int> expenses = { 450, 1200, 300, 800, 950, 60, 2200 };
    int page_no = 0;
    for (const auto& page : pages(expenses, 3)) {
        std::cout << "page " << ++page_no << ':';
        for (int e : page) std::cout << ' ' << e;
        std::cout << '\n';
    }
    return 0;
}

/* Output:
first 10 Fibonacci numbers: 0 1 1 2 3 5 8 13 21 34
first Fibonacci number above 1000: 1597
RCPT-2026 RCPT-2027 RCPT-2028
month 1: 5000
month 2: 10050
month 3: 15150
month 4: 20302
month 5: 25505
month 6: 30760
page 1: 450 1200 300
page 2: 800 950 60
page 3: 2200
*/