Skip to content

Coroutines

  • coroutines are functions that can suspend and resume their execution while keeping their state
  • resume and suspend are highly efficient and can be compared to the overhead of regular function calls
  • typically the client requests a coroutine object from a coroutine factory. The (repeated) calls to the coroutine are made through the coroutine object.
  • C++20 has a framework to write coroutines, functions to use: co_yield, co_await,…
  • for more infos see https://en.cppreference.com/w/cpp/language/coroutines

Example “Lazy generator”:

Assume that you need a simple list of numbers . Instead of requesting a long list of e.g. 1000 numbers and afterwards picking the needed numbers from the returned list, think of requesting each number at the moment when needed by a call to a coroutine, thus avoiding the overhead of returning/storing unneeded data.

Pseudocode:

CreateNumber GeneratorForNumbers(int begin) 
{
    for (int num=begin;; ++num) // infinite data stream, there is no limit on returned numbers!
    {
        co_yield num; // return each single value
        // the next client call to CreateNumber will proceed with this line
    }
}

// Client code:
const auto createNumber = GeneratorForNumbers(30);
for (int i = 1; i<=10; ++i) std::cout << createNumber() << "\n";
// => writes numbers 30,31,...,40 to stdout

In the example above GeneratorForNumbers is the coroutine factory and CreateNumber is the coroutine object which allows requesting for the next number when needed.