Threads & Concurrency Models

a coroutine

/ CO-roo-teen /

Think of reading a choose-your-own-adventure book where you can place a bookmark, set the book down to do something else, and later pick it up exactly where you left off — mid-sentence, with everything you remembered intact. A coroutine is a function that can do this: it can pause itself partway through, hand control back to whoever called it, and later resume from exactly the point it paused, with all its local variables still in place. An ordinary function only knows two moves — start and return; a coroutine adds suspend and resume.

Concretely, when a normal function returns, its local state is gone. A coroutine instead yields: it freezes its position and its local variables and gives control back, then continues from that frozen point when resumed. This makes coroutines a natural way to write code that waits — for input, for a network reply — without blocking a whole thread. Instead of a thread sitting idle on a slow read, the coroutine yields at the wait, lets other coroutines run, and is resumed when the data is ready. Crucially, coroutines are cooperatively scheduled: a coroutine keeps running until it chooses to yield. Nothing preempts it. This is the engine behind modern async/await: an await point is a place where the coroutine may suspend and let other work proceed.

Where this fits: coroutines are the building block under green threads and async tasks, and they shine for I/O-bound, mostly-waiting workloads on a single thread, with switching far cheaper than even user-level threads because the suspend points are explicit. The honest caveat is the flip side of cooperative scheduling — because a coroutine yields only when it decides to, a coroutine that runs a long CPU-bound loop without yielding will hog the thread and starve all the others. Coroutines give you cheap concurrency on one thread; for true parallelism you still need several threads or cores underneath.

With async/await, a download function can write: start the request, then await the reply. At the await, the coroutine suspends and the program runs other coroutines instead of blocking a thread; when the reply arrives, the coroutine resumes on the line right after the await, as if it had never paused.

A function that can pause and resume — the engine under async/await.

Coroutines are cooperatively scheduled: one that never yields will monopolize its thread and starve the rest. They give cheap single-thread concurrency, not parallelism — that still needs multiple threads or cores.

Also called
cooperative routineasync task (a close relative)協同程式共常式