C++20 Coroutines
Why Functions Sometimes Need a Break and What This Underrated Feature Can Do
by Michael Hava, MSc
When you read a book, you put a bookmark in it so you can pick up exactly where you left off later. In programming, this wasn’t always a given: a classic function runs from start to finish. Coroutines, on the other hand, can pause, return an intermediate result, and resume seamlessly later. They’ve been a permanent part of the language since C++20, yet so far only a few developers have been using them. Michael Hava, a member of the ISO C++ Standardization Committee, explains what’s behind the concept and why it deserves more attention now.
Contents

What Coroutines Are and What They’re Used For
Since 2011, a new C++ standard has been released every three years. Broadly speaking, a distinction can be made between major releases (C++98, C++11, C++20) and minor releases (C++14, C++17, C++23). C++20 introduced a wide range of new language and library extensions. While many of these extensions—such as concepts—were quickly embraced by the community, coroutines languished for a long time in undeserved obscurity and had a reputation as an “expert feature.”
But what exactly are coroutines? The concept was invented in 1958 by Melvin Conway, who published it in 1963 in his paper“Design of a Separable Transition-Diagram Compiler.”It is a generalization of the concept of a function or subroutine. Unlike functions, coroutines can interrupt their execution on their own, optionally return a result, and later resume at the point where they were interrupted.

Stack-oriented or stackless: two approaches
Programming languages can support coroutines in two ways: either stack-based as a special case of threads (often called fibers ), which allows for implementation as a library (such as Boost.Coroutine), or stackless as a dedicated, function-like language construct that is transformed by the compiler. Aside from specific implementation details, the most striking difference between these two approaches is where the coroutine can be interrupted: stackless coroutines allow interruption only directly within the coroutine itself, not in functions called from it. Stack-oriented coroutines can be interrupted at any time.
Depending on the use case, stackless or stack-oriented coroutines may be the better choice. For this reason, the C++ Standards Committee is working on a stack-oriented coroutine library (fiber_context) for a future version of the language. C++20 coroutines are stackless. Here is a minimal example:
auto func() -> Coroutine {
co_return;
}
Even this short code example highlights some of the unique features of C++20 coroutines. First, there’s the keyword `co_return` and the obvious discrepancy between `co_return;` and the `Coroutine` return type. It’s also worth noting that there is no syntactic marker to identify `func` as a coroutine—whether a function is a coroutine is an implementation detail in C++. The rule for the compiler is relatively simple: if a function contains at least one of the following keywords—co_return, co_await, or co_yield—then it is a coroutine. Coroutine—the so-called Coroutine Wrapper – is central to the C++20 design: it governs which keywords are valid within the coroutine and defines their semantics. It also manages the coroutine and defines the API through which it can be interacted with.
Undoubtedly, the initial use of coroutines was complicated by the fact that, while C++20 defines the basic language mechanism, it does not provide a coroutine wrapper. With C++23, the Standard Library was extended to include one: std::generator. This class models a sequence whose elements are computed during iteration. The following code example shows a simple use case, but the same mechanism can also be used for more complex tasks—such as processing the results of a database query.
auto bar() -> generator<int> {
for(auto i{10}; i < 15; ++i)
co_yield i; // i ist das nächste Element
co_return; // Optional wegen co_yield
}
auto foo() -> generator<int> {
co_await bar(); // Verwendung von co_await ist generell nicht erlaubt
co_yield 0;
co_yield 1;
co_yield 2;
co_yield ranges::elements_of{bar()}; // Leite alle Elemente von bar weiter
co_yield 3;
co_yield 4;
co_yield 5;
co_return 6; // co_return kann kein Element liefern
}
int main() {
for(auto i : foo() | views::filter(is_even) | views::transform(sqr))
println("{:>3}", i);
}
Ausgabe:
0
4
100
144
196
16
Outlook: Coroutines in C++26
The C++ Standards Committee plans to include another coroutine wrapper in the standard library in C++26: `std::execution::task`—an asynchronous task intended primarily for use with the new library for asynchronous and parallel computations. Practical examples of how to use this type would require an explanation of the underlying concepts of the new library, which is beyond the scope of this article. Therefore, the code example below is limited to an overview of the specific features of this coroutine implementation.
auto bar() -> execution::task<int> {
co_yield 5; // Verwendung von co_yield ist hier nicht erlaubt
co_return 10; // Liefert Ergebnis
}
auto foo() -> execution::task<void> {
auto tmp{co_await bar()}; // Warte auf Ergebnis von bar
println("{}", tmp);
co_return; // Nur in task erlaubt; optional wegen co_await
}
int main() {
this_thread::sync_wait(foo()); // Warte synchron auf task
}
Ausgabe:
10
struct customization {
using error_types = execution::completion_signatures<
// Aktiviere Unterstützung für co_yield execution::with_error um
// ohne Ausnahme die Ausführung des Tasks abzubrechen
execution::set_error_t(int)
>;
};
auto baz() -> execution::task<void, customization> {
println("going to yield");
co_yield execution::with_error<int>{1}; // Koroutine wird hier abgebrochen!
println("resumed"); // Wird niemals ausgeführt
}
int main() {
try {
this_thread::sync_wait(baz()); // Warte synchron auf task
} catch(int error) { // task wurde mit with_error abgebrochen
println("error: {}", error);
}
}
Ausgabe:
going to yield
error: 1
It is expected that the components of the standard library will cover the most common use cases for coroutines, thus ensuring that coroutines no longer remain in the shadows. Thanks to the flexible design, specific problems can always be addressed using custom coroutine wrappers . As an example, I would like to mention my own library for cooperative, interruptible tasks and generators , developed for RISC Software GmbH, which allows long-running tasks to be paused and subsequently terminated.
About Michael Hava
Michael Hava, Senior Software Architect and C++ expert at RISC Software GmbH, is a member of the C++ Committee. He joined RISC Software in 2011 while pursuing his master’s degree at the University of Applied Sciences Upper Austria—Hagenberg Campus. Since then, he has promoted the adoption of modern C++ in various technical fields. After attending his first C++ standardization meeting in 2019, he became a founding member of the Austrian C++ Working Group and serves as chair of the national committee. He works primarily in the Library Evolution Working Group (LEWG), and several of his papers are currently focused on C++26 and C++29.
Ansprechperson
Michael Hava, MSc
Senior Software Architect