Coroutines
A coroutine is a function that can pause partway and carry on later. Seven steps show how pausing lets many tasks share one thread, and how that differs from threads.
In 30 seconds
A coroutine is a function that can suspend itself partway through, give control back, and later resume from the same spot with its variables intact.
That makes cooperative multitasking possible: many coroutines share one thread, and each lets the others run whenever it has to wait. Generators pause at yield; async functions pause at await.
Unlike threads, coroutines are never interrupted by the system. They are cheap and predictable, but one that refuses to pause holds everyone up.
Coroutines, step by step
Shown: single-threaded coroutines, as in Python’s asyncio and JavaScript; Go and Kotlin spread them over several threads. Timelines are schematic. CPython’s global lock limits how far its threads run in parallel.
- Step 1: A normal call runs to the end. An ordinary function has one way in and one way out. The caller stops, the function runs its whole body from the first line to a return, and only then does the caller carry on. Nothing of the function survives the return: call it again and it starts from the top.
- Step 2: A coroutine can pause midway. A coroutine is a function that can stop partway, hand control back, and later continue from exactly where it stopped, with its local variables intact. While it is paused, the caller is free to do other work. It can pause and resume many times before it finally finishes.
- Step 3: Generators already do this. A Python generator is a simple coroutine. Each yield suspends it and passes a value out. send resumes it and passes a value in: here "Ada" becomes the result of the first yield and is stored in name. Pausing and resuming, with values passing both ways, is all a coroutine is.
- Step 4: await: pause until ready. async def defines a coroutine, and await marks the places where it may pause: here, while a 2-second timer runs. tea and toast are started together with asyncio.gather. When tea pauses, toast gets its turn, so the two waits overlap and everything finishes after 2 seconds instead of 3.
- Step 5: The event loop takes turns. Something has to resume paused coroutines. That is the event loop: plain code that keeps a list of coroutines ready to continue. It resumes one and lets it run until its next await, then picks another. When a timer fires or data arrives, the coroutine that was waiting for it rejoins the ready list.
- Step 6: It only works if they give way. This is cooperative multitasking: the loop never interrupts anyone. A switch can happen only when the running coroutine reaches an await. Replace the await with a blocking time.sleep(2) and tea holds the only thread for 2 seconds. toast cannot even start, and the total rises to 3 seconds.
- Step 7: Coroutines vs threads. Threads are switched by the operating system at any instant and can run on several cores at once, so shared data needs locks. Each thread also reserves its own stack. Coroutines switch only at an await and, in Python or JavaScript, share one thread: light enough to run by the thousand, but no help for heavy computation.
Try it yourself
Learn this first
Learn next
- Concurrency vs parallelismTaking turns on one core versus truly running at once on several. Intermediate
- Goroutines and channelsLightweight Go functions that run side by side and pass values through channels. Intermediate
- Race conditionsTwo threads update one counter and an update vanishes, unless a lock steps in. Intermediate
Spotted a mistake on this page?