Skip to content

C++ Coroutine

Primer

lewissbaker Coroutine Theory

lewissbaker Coroutine Theory

lewissbaker Understanding operator co_await

cppreference Coroutines (C++20)

A function is a coroutine if its definition does any of the following:

1) uses the co_await operator to suspend execution until resumed

task<> tcp_echo_server() {
  char data[1024];
  for (;;) {
    size_t n = co_await socket.async_read_some(buffer(data));
    co_await async_write(socket, buffer(data, n));
  }
}

2) uses the keyword co_yield to suspend execution returning a value

generator<int> iota(int n = 0) {
  while(true)
    co_yield n++;
}

3) uses the keyword co_return to complete execution returning a value

lazy<int> f() {
  co_return 7;
}

Implementation

Before C++20

lewissbaker/cppcoro

The 'cppcoro' library provides a large set of general-purpose primitives for making use of the coroutines TS proposal described in N4680.

boost Coroutine2

C++11

TODO

paoloseverini Async-Await in C++

stackoverflow What are the mechanics of coroutines in C++20?