Coroutines
In short: Coroutines are functions that can pause midway and later resume at the same spot.
In more detail: Unlike threads, it is not the operating system that switches but the code that hands over control voluntarily (cooperative multitasking). That makes them very lightweight: tens of thousands run in one thread.
In Depth
- Keywords:
yield(Python generators),await(async/await),suspend(Kotlin), goroutines (Go, scheduled by the runtime). - Strength: Lots of waiting on network or database without idle threads piling up.
- Weakness: A coroutine that computes instead of waiting blocks all others on the same thread. CPU-heavy work belongs in processes or threads.
- Flow: An event loop starts coroutines, remembers their state and resumes them once their result is ready.
- Under the hood: The compiler usually turns them into a state machine.
See also: async/await