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
- Kinds: Fiber
- Is used by: Async functions as state machines
- See also: Async and await, Green threads and M:N scheduling, Suspension point
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¶
- In the books: Async Rust, Maxwell Flitton, Caroline Morton — ch. 5, 'Coroutines'
- In the books: Concurrency with Modern C++, Rainer Grimm — ch. 6, 'The Future: C++20/23' → 'Coroutines'
- In the books: Python Concurrency with asyncio, Matthew Fowler — ch. 2, 'asyncio basics' → 'Introducing coroutines'
- In the books: JavaScript Concurrency, Adam Boduch — ch. 4, 'Lazy Evaluation with Generators' → 'Coroutines'
- In the books: Kotlin Coroutines by Tutorials, Filip Babić, Nishant Srivastava — ch. 1, 'What Is Asynchronous Programming' → 'Explaining coroutines: The inner works'
- In the books: Asynchronous Programming in Rust, Carl Fredrik Samson — ch. 2, 'How Programming Languages Model Asynchronous Program Flow' → 'Coroutines: promises and futures'
- Notes: coroutine - python - async ↗
- Reference: Wikipedia: Coroutine ↗