The consume_items function is also a coroutine. The function produce_items() below is a coroutine, because it uses the co_yield keyword to return a value and has the return type cppcoro::generator that satisfies the requirements of a generator coroutine. A task represents an asynchronous computation that is executed lazily (that means only when the coroutine is awaited) and a generator is a sequence of values of some T type, that are produced lazily (that is, when the begin() function is called to retrieve an iterator or the ++ operator is called on the iterator). The cppcoro library contains abstractions for the C++20 coroutines, including task, generator, and async_generator.
In this post, I’ll show how to write some simple examples using the cppcoro library. That means, we need to either write our own or rely on 3rd party libraries for this. However, the C++20 standard, only defines a framework for the execution of coroutines, but does not define any coroutine types satisfying such requirements.
the co_yield keyword to suspend execution and return a valueĪ coroutine must also have a return type that satisfies some requirements.the co_return keyword to complete execution and optionally return a value.the co_await operator to suspend execution until resumed.A function becomes a coroutine if it uses any of the following: A coroutine is a function that has the ability to be suspended and resumed.
One of the most important new features in the C++20 is coroutines.