Skip to content

Coroutine

Category: Units of execution · Status: stub · Lessons: chapter 06, Async (planned)

One line: A function that can suspend itself part-way through and be resumed later from the same point, keeping its local state in between.

Also called: asymmetric coroutine, symmetric coroutine, generator, stackless coroutine.

How it connects

flowchart LR
  n_async_state_machine["Async functions as state machines"]
  n_coroutine["Coroutine"]
  n_fiber["Fiber"]
  n_async_state_machine -->|uses| n_coroutine
  n_fiber -->|is a| n_coroutine
  classDef center stroke-width:3px
  class n_coroutine center
  classDef outside stroke-dasharray: 4 3
  class n_async_state_machine,n_fiber outside

In each language

Rust async blocks produce a Future; general coroutines ↗ are unstable
C++ C++20 coroutines ↗ are stackless, with co_await, co_yield and co_return; C++23 adds std::generator
Python Coroutines ↗ are written with async def; generators ↗ with yield are the other kind
C# Iterators with yield return, and async methods
JavaScript Generator functions ↗ (function*, yield) and async functions
Kotlin Coroutines ↗: the language supplies suspend, and builders such as launch come from kotlinx.coroutines
Elsewhere Lua's coroutines ↗, also called collaborative multithreading, suspend only by explicitly calling a yield function

Where to read more