Lesson 49 of 55
10 mins readPython Coroutines & Cooperative Multitasking
In Plain English
Coroutines (threads) enable cooperative multitasking. A coroutine can suspend execution with `coroutine.yield()` and resume right where it left off with `coroutine.resume()`.
Deep Dive: How It Works
coroutine.create(fn): Returns a new coroutine (type `thread`) in `suspended` state.
coroutine.resume(co, ...): Starts or resumes execution, passing arguments into the coroutine.
coroutine.yield(...): Pauses the coroutine and returns values back to the resuming caller.
Generators: Building infinite Fibonacci sequences or data stream pipelines.
Core Rules to Remember

Cooperative Multitasking: Coroutines explicitly yield control; no preemption or race conditions.

Bidirectional Data Passing: Pass values in via `resume` and receive values out via `yield`.
Live Interactive Example
Hit Run Code to see it liveProducer-Consumer Generator with Coroutines
Python 3.12
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Output Console
Click "Run Code" to view the rendered output.
How it works: coroutine.yield paused the generator and resume fetched the next number.
Your Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Micro Exercise
Step Coroutine Yields
Create `local co = coroutine.create(function() coroutine.yield("Step 1") return "Step 2" end)`.
Call `coroutine.resume(co)` twice and print both returned values.
1
2
Sandbox Output
Click "Run & Check" to test your solution.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.