It's hard to write coroutine-based code from scratch. C++20 only offers the fundamental utilities for writing coroutines, so we need a set of primitives to use when writing our own coroutines. The cppcoro library created by Lewis Baker is one of the most commonly used coroutine frameworks for C++. In this section, we'll showcase the library and demonstrate how to use it when writing coroutine-based code.
Let's start with an overview of the coroutine types the library offers us:
- task<>: For scheduling work to be executed later – starts executing when it's co_awaited for.
- shared_task<>: A task that multiple coroutines can await. It can be copied so that multiple coroutines reference the same result. Doesn't offer any thread-safety on its own.
- generator: Produces a sequence of Ts lazily and synchronously. It's effectively a std::range: it has a begin() returning an iterator and an end() returning a...