Choose Threads or Processes for the Workload
Core idea
In ordinary GIL-enabled CPython, one thread at a time executes Python bytecode within an interpreter. Threads can overlap waiting on I/O, and native extensions may release the GIL. Separate processes can execute CPU work on multiple cores, but data transfer and startup add overhead. Concurrency is overlapping progress; parallelism is simultaneous execution. Measure representative work instead of promising speedup.
def score(values): return sum(n*n for n in values)batches = [[1, 2], [3, 4]]print([score(batch) for batch in batches])This is a baseline with no worker startup or transfer costs.
Expected output:
[5, 25]Compute the same results with threads
from concurrent.futures import ThreadPoolExecutordef score(values): return sum(n*n for n in values)with ThreadPoolExecutor(max_workers=2) as pool: print(list(pool.map(score, [[1, 2], [3, 4]])))Equal answers do not establish parallel execution or faster CPU performance.
Expected output:
[5, 25]Common mistake
The GIL is not an application-level lock for compound invariants. Do not infer performance from a small deterministic example or assume every Python implementation has the same GIL behavior.
Practice
Compare sequential, thread-pool and process-pool designs for a larger independent CPU workload. Separately design an I/O-bound test; report runtime build, input size and repeated measurements.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
GIL versus parallelism
Check your understanding of gil versus parallelism.
What is printed?
print(sum(n*n for n in [2,3]))What is printed?
from concurrent.futures import ThreadPoolExecutorwith ThreadPoolExecutor(2) as p: print(list(p.map(abs,[-2,4])))Which workload often benefits from threads on GIL-enabled CPython?
Why compare against a sequential baseline?