Implementing basic coroutines
In the previous section, we studied the basics of coroutines, what they are, and some use cases.
In this section, we will implement three simple coroutines to illustrate the basics of implementing and working with them:
- The simplest coroutine that just returns
- A coroutine sending values back to the caller
- A coroutine getting values from the caller
The simplest coroutine
We know that a coroutine is a function that can suspend itself and can be resumed by the caller. We also know that the compiler identifies a function as a coroutine if it uses at least one co_yield
, co_await
, or co_return
expression.
The compiler will transform the coroutine source code and create some data structures and functions to make the coroutine functional and capable of being suspended and resumed. This is required to keep the coroutine state and be able to communicate with the coroutine.
The compiler will take care of all those details but bear...