Skip to main content
Albero Academy

Threading

Run tasks in parallel threads — and understand the GIL.

Advanced Python10 min

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:

a thread pool
from concurrent.futures import ThreadPoolExecutor
def download(url):
... # I/O-bound: mostly waiting on the network
with 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

  1. 01Threads run concurrently within one process and share memory.
  2. 02ThreadPoolExecutor is the easy high-level API; pool.map runs work concurrently.
  3. 03The GIL lets only one thread run Python bytecode at a time.
  4. 04Threads help I/O-bound work (waiting), not CPU-bound work — use multiprocessing for that.
  5. 05Guard shared mutable state with a Lock to avoid race conditions.

Finished this chapter?

Mark it complete to track your progress through Python.