Introduction to Coroutines

This lesson gives an overview of coroutines, predicted to be introduced in C++20.

We'll cover the following

Coroutines are functions that can suspend and resume their execution while keeping their state. The evolution of functions goes one step further in C++20.

What I present in this section as a new idea in C++20 is actually quite old. The term coroutine was coined by Melvin Conway; He used it in his publication on compiler construction in 1963. Likewise, Donald Knuth called procedures a special case of coroutines. Sometimes, it just takes a while to get your ideas accepted.

With the new keywords co_await and co_yield, C++20 will extend the execution of a C++ function with two new concepts.

Thanks to co_await expression it will be possible to suspend and resume the execution of the expression. If you use co_await expression in a function func, the call auto getResult= func() will not block if the result of the function is not available. Instead of resource-consuming blocking, you have resource-friendly waiting.

co_yield expression allows it to write a generator function that returns a new value each time. A generator function is a kind of data stream from which you can pick values. The data stream can be infinite, therefore, we are in the center of lazy evaluation with C++.

A Generator Function

The following program is as simple as possible. The function getNumbers returns all integers from begin to end, incremented by inc. In that case, begin has to be smaller than end, and inc has to be positive.

Get hands-on with 1200+ tech skills courses.