
Code
Pick the Right Tool
Experienced developers ask two questions before adding concurrency:
- Is there more than one job? If not, plain code is simplest.
- Where does the time go? Waiting on I/O (network, disk, timers), or computing on the CPU?
Then they pick:
- CPU-bound: use processes (on standard CPython)
- I/O-bound, and async libraries exist: use asyncio
- I/O-bound, but only blocking libraries: use threads
On a real machine, concurrent.futures gives threads and processes the
same friendly interface:
from concurrent.futures import ProcessPoolExecutor
with ProcessPoolExecutor() as pool:
results = list(pool.map(crunch, datasets))
Swap in ThreadPoolExecutor and the rest of the code stays the same.
Assignment
A job is a dict like
{"name": "maps", "kind": "io", "count": 40, "async_ok": True}.
choose_tool(job)returns:"plain"ifcountis 1 or less (check this first)"processes"ifkindis"cpu""asyncio"ifkindis"io"andasync_okis true"threads"ifkindis"io"otherwise (async_okmay be missing; treat that as false)- raise
ValueErrorfor any other kind
plan(jobs)returns a dict that maps each tool to the list of job names that use it, keeping the input order. Include only tools that are actually used.
A job is a dict like
{"name": "maps", "kind": "io", "count": 40, "async_ok": True}.
choose_tool(job)returns:"plain"ifcountis 1 or less (check this first)"processes"ifkindis"cpu""asyncio"ifkindis"io"andasync_okis true"threads"ifkindis"io"otherwise (async_okmay be missing; treat that as false)- raise
ValueErrorfor any other kind
plan(jobs)returns a dict that maps each tool to the list of job names that use it, keeping the input order. Include only tools that are actually used.
main.py Python sleeping
Press Run to try your code, then Check to test it.