Multiprocessing runs work in separate processes. Asyncio coordinates tasks that can suspend while waiting, usually on one event-loop thread.
Compare isolation and scheduling, inspect actual suspension points and choose an approach based on the work’s bottleneck.
A pipeline can be slow because it waits for other systems or because it computes. Async tasks overlap suitable waits; process workers can distribute independent computation. Follow when a task actually suspends, bound the amount of active work, and define what timeout or failure should do to the remaining work. Real loop and process labs below run locally.

Juggle many waits on one thread
Two coroutines, run concurrently with gather. Watch when each print
happens, not just the final result:
import asyncio
async def worker(name):
print(f"{name} start")
await asyncio.sleep(0) # "I'm waiting — someone else can run now"
print(f"{name} end")
async def main():
await asyncio.gather(worker("A"), worker("B"))
asyncio.run(main())On a local CPython loop with the normal task factory, these zero-delay sleeps let both tasks start before either resumes. This is a small scheduling observation, not a promise that every await yields or every loop uses the same ordering. The predictions below use that same local setup.
import asyncio
async def worker(name, wait):
print(f"{name} start", end=" ")
await asyncio.sleep(wait)
print(f"{name} end", end=" ")
async def main():
await asyncio.gather(worker("A", 0), worker("B", 0), worker("C", 0))
asyncio.run(main())A real async function usually awaits something that actually takes time —
a network call, a database query — not asyncio.sleep(0). The sleep(0) is
just the smallest possible "I'll wait here," used to make the ordering
visible without actually waiting.
Preparing this topic’s interactive investigation…
A possible suspension is not a promised turn
Calling an async def function creates a coroutine object; it does not automatically run it. Awaiting that coroutine runs it as part of the current task. Creating a task schedules it independently. Most importantly, await only suspends when the awaited operation needs to wait: an already-completed awaitable or a coroutine that returns immediately can finish without giving another task a turn.
This is a local Python 3.13+ lab, not a browser Run block:
import asyncio
async def immediate():
return 120
async def other():
print("other task")
async def main():
task = asyncio.create_task(other())
print("before")
value = await immediate()
print("after", value)
await asyncio.sleep(0) # explicitly suspends this task
await task
asyncio.run(main())With the normal task factory, after 120 appears before other task. The await immediate() did not suspend. asyncio.sleep(0) does suspend, but real socket completion order is determined by readiness and scheduling, not a universal round-robin guarantee. gather returns results in input order; that is different from execution or completion order.
Ordinary open(...).read() remains blocking inside async def; writing await near it does not change the file API. On local Python, a blocking I/O call can sometimes be moved to asyncio.to_thread, while network/database work needs an appropriate async client. That thread facility is not available in this Pyodide worker.
asyncio.run owns a top-level loop and cannot be nested in an already-running loop on the same thread. Run these examples locally. The browser runtime uses a different event loop; the round_robin exercise models scheduling and does not run asyncio.
References: tasks and awaitables, asyncio runners, and Pyodide limitations.
Bound work and make cancellation part of the contract
A request for 5,000 URLs is not permission to open 5,000 connections at once. Limit active operations, set a deadline, and decide what a failed member means for the batch. A semaphore caps active work; it does not by itself cap the number of task objects queued in memory. For a very large stream, use a bounded queue and a fixed worker set.
Local lab, Python 3.11+:
import asyncio
async def inspect_batch(delays):
limit = asyncio.Semaphore(2)
active = peak = 0
async def inspect(index, delay):
nonlocal active, peak
async with limit:
active += 1
peak = max(peak, active)
try:
await asyncio.sleep(delay) # controlled stand-in for async I/O
return index
finally:
active -= 1
async with asyncio.timeout(0.1):
async with asyncio.TaskGroup() as group:
tasks = [group.create_task(inspect(i, d)) for i, d in enumerate(delays)]
return [task.result() for task in tasks], peak
async def main():
try:
print(await inspect_batch([0.01, 0.01, 0.01]))
except TimeoutError:
print("batch deadline exceeded; unfinished tasks cancelled")
asyncio.run(main())Change the last delay to 1 second. Observe the timeout path, and explain why cleanup still decrements active. Task cancellation is cooperative, delivered as CancelledError at a cancellation opportunity; cleanup in finally is where owned resources are released. Do not swallow cancellation merely to keep a task alive. A timeout cannot forcibly stop CPU code that never yields or guarantee that a remote side effect was undone. TaskGroup waits for its members and cancels siblings on ordinary member failure; gather has different failure semantics.
References: semaphores, cancellation and task groups, and blocking work on an event loop.
multiprocessing.Pool for real CPU parallelism
An event loop does not make a pure-Python CPU loop execute on several cores. A process pool is one way to parallelize independent CPU work. Native code that releases the GIL and compatible free-threaded builds are other possibilities; benchmark the relevant workload. Run the following as a saved local script, not in the browser:
from multiprocessing import get_context
def square(n):
return n * n
if __name__ == "__main__":
with get_context("spawn").Pool(processes=4) as pool:
results = pool.map(square, range(10))
print(results) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]pool.map sends chunks of range(10) to separate OS processes, each
computing square independently, genuinely in parallel. Pool arguments and results normally cross a serialization boundary, so
functions and values must be picklable and worker functions should be
importable at module level. A lambda or nested function can fail here.
Separate processes do not share ordinary Python object updates; explicit
shared memory or IPC is a separate design. Tiny square calls demonstrate
the API, not a speedup—startup and copying can cost more than the work.
With the explicitly selected spawn context, a child starts a new interpreter
and imports the main module. The if __name__ == "__main__": guard prevents
that import from recursively creating another pool. Save the code in a .py
file; interactive definitions may not be importable by children. Defaults
vary: Windows and macOS use spawn; Python 3.14 changed the default on
supported POSIX systems to forkserver, and fork is no longer the default
anywhere. Choose a compatible context deliberately rather than relying on
a platform accident. See the 3.13 process guidelines
and 3.14 start-method changes.
Picking threads, processes, or asyncio
The question that decides it is always the same one from the previous lesson — is the work waiting, or computing? — plus one more: how many things are waiting at once.
| best for | why | |
|---|---|---|
| threading | blocking I/O through a bounded worker pool | shared memory; suitable libraries release the GIL during waits |
| asyncio | many waits supported by async APIs | tasks share a loop; limit active requests and queued work |
| multiprocessing | CPU-bound work | separate GILs, real parallel cores — can parallelize independent CPU work; startup and serialization may dominate |
A web scraper needs to fetch 5,000 URLs. Each request mostly waits on the network. Which tool scales best to that many concurrent waits on one machine?
Quick practice
import asyncio
async def step(name, n):
for i in range(n):
print(f"{name}{i}", end=" ")
await asyncio.sleep(0)
async def main():
await asyncio.gather(step("A", 2), step("B", 2))
asyncio.run(main())Inside one asyncio coroutine, between two await points, can another coroutine on the SAME event loop run and change a variable this one is using?
🎯 Your turn
Write round_robin(tasks). tasks is a list of task step-lists — each inner
list is one cooperative task's steps, in order, as strings (like a
coroutine's print statements between its awaits). Simulate a round-robin
scheduler: in each round, give every task that still has steps left exactly
ONE step, in task order, then start the next round. Keep going until every
task is exhausted. Return the full execution trace as one flat list.
round_robin([["a1", "a2"], ["b1", "b2", "b3"]])→["a1", "b1", "a2", "b2", "b3"]
Hint: track each task's current position with a list of indices, one per task; loop rounds until every position has reached the end of its task.
Press ▶ Run, try the Live App chips, then ✓ Check. After that, the practice set below builds variations on the same scheduler — bursts of work per turn, and a configurable priority order.
Practice — level up
0/5 solvedSolve each in its own editor — Run to try, Check to grade. Stuck? Reveal a Hint, or the full Solution + walkthrough.
Write has_more(task, pos). Return True if position pos is still a valid index into task (the task isn't finished yet).
Write remaining_indices(tasks, positions). positions is a list of the current position for each task (same length as tasks). Return a list of the INDICES of tasks that still have steps left.
Write one_round(tasks, positions). Give every task that still has a step left exactly one step, in task order. Return [steps_taken, new_positions] — the list of steps taken this round, and the updated positions list.
Write round_robin_burst(tasks, burst). Like round_robin, but each task gets up to burst CONSECUTIVE steps per turn (fewer if it runs out) before the scheduler moves to the next task.
Write round_robin_priority(tasks, order). order is a list of task indices giving the order to check tasks in EACH round (instead of always 0, 1, 2, ...). Each round, visit the tasks in order, giving one step to each that still has work.