Intermediate Topic 20 of 51 Concurrency & Parallelism
Coroutines
Functions that suspend and resume cooperatively.
How it works
A coroutine is a function that can suspend its execution and later resume where it left off, preserving local state, allowing cooperative multitasking within one thread. Unlike threads, coroutines are scheduled by the program rather than by the operating system, and switching is cheap, so thousands or millions can exist. They can be stackful, saving a whole call stack as in Lua and Go's goroutines, or stackless, as in Python generators-based async, C++20 and Kotlin, transformed into state machines. Generators are a special case yielding values.
Where it is used
Asynchronous I/O frameworks, game scripting of sequences over many frames, generators for lazy sequences and simulation of many concurrent activities use coroutines.
Common pitfall
Cooperative scheduling means a coroutine that never yields blocks the others. Debugging stack traces across suspension points is harder. Mixing blocking calls inside coroutines stalls the scheduler. Cancellation and exception propagation need structure, such as structured concurrency. Understand the scheduler, yield points and lifetime of captured data.
Where it fits in the course
Coroutines is topic 20 of 51 in Concurrency & Parallelism, rated Intermediate. It follows Event-Driven Concurrency. The next topic is Futures and Promises Model.
Practice and explore
- Open the interactive lesson, with a mini quiz.
- Take the Concurrency & Parallelism quiz.
How to study this topic
- Read the explanation above and restate the definition in your own words.
- Open the interactive lesson and answer its mini quiz.
- Read the common pitfall, then write a short example that avoids it.
- Check your understanding in the Concurrency & Parallelism quiz, and revisit the topic if you miss a question.
Frequently asked questions
What is Coroutines?
Where do people use Coroutines?
What is the most common mistake with Coroutines?
What should I learn before this topic?
How can I practice it?
Is Coroutines hard to learn?
How long does it take to learn Coroutines?
Which topics are related to Coroutines?
What should I study after Coroutines?
Related topics
- Event-Driven Concurrency (Concurrency & Parallelism)
- Futures and Promises Model (Concurrency & Parallelism)
- Async/Await (Concurrency & Parallelism)
- Green Threads (Concurrency & Parallelism)