Threads let multiple tasks run concurrently within one process, sharing memory. They're a classic way to overlap I/O-bound work — but Python's GIL means they don't speed up pure computation, which surprises many newcomers.
The easy API: ThreadPoolExecutor
You rarely manage raw threads — a pool handles the details. map runs the function over inputs, several at a time:
from concurrent.futures import ThreadPoolExecutordef download(url):... # I/O-bound: mostly waiting on the networkwith ThreadPoolExecutor(max_workers=5) as pool:results = list(pool.map(download, urls)) # up to 5 concurrent downloads
The GIL
Shared state needs care
Because threads share memory, two threads updating the same variable can corrupt it (a race condition). Protect shared mutable state with a Lock, or avoid sharing by passing data through a queue.Queue.
Key takeaways
- 01Threads run concurrently within one process and share memory.
- 02ThreadPoolExecutor is the easy high-level API; pool.map runs work concurrently.
- 03The GIL lets only one thread run Python bytecode at a time.
- 04Threads help I/O-bound work (waiting), not CPU-bound work — use multiprocessing for that.
- 05Guard shared mutable state with a Lock to avoid race conditions.
