Code

Pick the Right Tool

Experienced developers ask two questions before adding concurrency:

  1. Is there more than one job? If not, plain code is simplest.
  2. 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}.

  1. choose_tool(job) returns:
    • "plain" if count is 1 or less (check this first)
    • "processes" if kind is "cpu"
    • "asyncio" if kind is "io" and async_ok is true
    • "threads" if kind is "io" otherwise (async_ok may be missing; treat that as false)
    • raise ValueError for any other kind
  2. 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.