Coroutines
Introduction / Definition
A coroutine can suspend execution and later resume from its previous point. Unlike an ordinary subroutine, it can yield control multiple times. Coroutines are useful for generators, pipelines, simulations, and asynchronous workflows. The suspended state must be retained.
Syntax / Structure / Formula
start → run → yield → resume → yield
Detailed Explanation
A generator is a familiar coroutine-like abstraction: each yield returns a value while preserving execution state.
Example
Example: A Python generator yields numbers one at a time.
Output / Result
The caller receives values incrementally without restarting the generator.
Important Points / Notes
- Control transfer is cooperative.
- Useful for incremental computation.
Mini Practice Question
How does a coroutine differ from a normal function call?