Threads, processes, and how an event loop works
🌍 In real life. Picture three kitchens:
- one cook switching between dishes (stir the dal, check the rice, flip the egg): that's asyncio, one worker taking turns
- several cooks in one kitchen, sharing the same fridge and stove: that's threads. They share everything, so two cooks grabbing the last egg at once is a real problem (that's what a
threading.Lockprevents) - several separate kitchens, each with its own fridge: that's processes. Nothing is shared by accident, and they truly cook at the same time, but passing food between kitchens takes effort
In the usual Python, only one thread runs Python code at any moment (the "GIL"), so threads help with waiting (downloads, files), not with heavy calculating. For heavy calculating, processes use several CPU cores. Python 3.13 also offers an optional build without the GIL.
The idea in one sentence: asyncio is one worker taking turns at waits, threads are several workers sharing the same memory, and processes are separate workers with their own memory; pick by whether the job mostly waits or mostly calculates.
Its words:
- event loop: the scheduler that runs one coroutine until it pauses, then the next
- thread: a worker inside the same program, sharing its data
- process: a separate program with its own memory, for heavy calculation
- I/O-bound vs CPU-bound: mostly waiting vs mostly computing
Step by step, how the event loop takes turns:
- It takes the first ready coroutine and runs it until it reaches an
awaitthat has to wait. - It puts that one aside and runs the next ready one.
- When a wait is over, that coroutine becomes ready again and gets its next turn.
Which one to reach for:
- lots of waiting (web requests, timers, files): asyncio, or threads for code that isn't async
- heavy number crunching (resizing a thousand photos): processes, through
ProcessPoolExecutor(fromconcurrent.futures)
Python in the browser has a single thread and can't start new processes, so the next two examples stop with an error here. On your own computer they run, and the note says what they print.
import threading
def cook(dish):
print("cooking", dish)
cooks = [threading.Thread(target=cook, args=(d,)) for d in ["rice", "dal"]]
for t in cooks:
t.start()
for t in cooks:
t.join()
print("all cooked")from concurrent.futures import ProcessPoolExecutor
def heavy(n):
return sum(i * i for i in range(n))
with ProcessPoolExecutor() as pool:
print(list(pool.map(heavy, [10, 100, 1000])))How does one worker take turns? An event loop is simpler than it sounds. Each piece of work is something that can pause and be resumed later, like a generator (Chapter 26). The loop keeps a queue: it takes the first job, runs it until it pauses, puts it at the back of the queue, and picks the next one. A job that finishes leaves the queue. Here is a whole event loop in a few lines, using generators that yield where asyncio would await:
from collections import deque
def cook(dish, steps):
for i in range(1, steps + 1):
print(dish, "step", i)
yield
print(dish, "done")
queue = deque([cook("tea", 2), cook("toast", 3)])
while queue:
job = queue.popleft()
try:
next(job)
queue.append(job)
except StopIteration:
passWhy not always use threads? Threads share everything, so two of them changing the same list at the same moment can corrupt it unless you add locks, and in standard Python only one thread runs Python code at a time, so threads don't speed up calculation. asyncio avoids the sharing problem by switching only at await; processes avoid it by sharing nothing.
Mistakes and edge cases.
- asyncio for heavy maths. A coroutine that calculates without any
awaitnever lets the others run. - Calling a coroutine without await.
f()on its own only makes a coroutine object and runs nothing (Python warns "coroutine was never awaited"). - await outside async. At the top level of a script,
await asyncio.sleep(1)givesSyntaxError: 'await' outside function; useasyncio.run(main()). - Threads in the browser. The Python in this app has no threads, so examples here use asyncio.
Quiz
You need to resize a thousand photos (heavy calculating). Which helps most in normal Python?
- Processes, one per CPU core
- asyncio
- Threads
Which workers share the same memory, so they must be careful not to change the same thing at once?
- Threads
- Processes
- Neither
What does this print?
def job(name): yield print(name) jobs = [job("a"), job("b")] for j in jobs: next(j) for j in jobs: next(j, None)What does the GIL mean for threads in the usual Python?
- Only one thread runs Python code at a time
- Threads can't wait for files
- Only one thread can be created
What does this print?
from collections import deque def count(name, n): for i in range(n): yield print(name, "finished") queue = deque([count("long", 3), count("short", 1)]) while queue: job = queue.popleft() try: next(job) queue.append(job) except StopIteration: passWhich line stops this script with a SyntaxError?
import asyncio print("waiting") await asyncio.sleep(0.1) print("done")
Coding tasks
Write
run_all(jobs: list) -> list: a tiny event loop.jobsis a list of generators. Take turns, as in the lesson: run the first job to its nextyield, collect the value it yields, put it at the back, and so on, until every job is finished. Give back every yielded value in the order they came.A pool of workers shares out a job like cards being dealt. Write
deal(items: list, workers: int) -> list[list]: give the first item to worker 0, the next to worker 1, and so on, going round again after the last worker. Give back each worker's items.