Stop 14 · Advanced PythonTopics · 4/8

threading & concurrent.futures

Part of the Python Roadmap

In short

Checking 50 websites one by one means 50 waits in a row. With a thread pool, the waits overlap and the whole job can finish in the time of a handful of requests.

The threading module runs functions in threads, and concurrent.futures.ThreadPoolExecutor offers a simpler, higher-level way to run many tasks at once and collect their results. Use locks when threads change shared data.

The jaadu acts as team leader in a cheerful call centre, handing index cards from a tall stack to a row of helpers wearing headsets.

Think of it like this

A call centre team

One person calling 40 customers spends most of the day listening to ringing tones. A team of eight shares the list: whoever is free picks the next number. ThreadPoolExecutor is that team. You hand over the list of jobs and it gives each free worker the next one, then collects every result for you.

Watch it happen

A pool of 3 workers pulling from a job queue

enqueue(python.org)
python.org

Front of the queue is coloured

1/7submit() puts the first job in the queue.

The big ideas

What you need to know

ThreadPoolExecutor

Creates a fixed number of worker threads. Use it in a with block so it waits for all work and shuts down cleanly.

submit() and map()

submit(fn, arg) returns a Future for one call. map(fn, items) runs fn on every item and returns results in input order.

as_completed()

Yields futures as they finish, fastest first, so you can show progress or handle errors one by one.

Lock shared data

When threads change the same variable or list, wrap the change in with lock: so updates don't get lost.

See it in code

Walk through the code

python
1import threading2from concurrent.futures import ThreadPoolExecutor, as_completed3 4import requests5 6URLS = [7    "https://www.python.org",8    "https://pypi.org",9    "https://docs.python.org/3/",10    "https://example.com",11]12 13total_bytes = 014lock = threading.Lock()15 16def fetch(url: str) -> tuple[str, int]:17    global total_bytes18    response = requests.get(url, timeout=10)19    size = len(response.content)20    with lock:21        total_bytes += size22    return url, size23 24with ThreadPoolExecutor(max_workers=4) as pool:25    futures = [pool.submit(fetch, url) for url in URLS]26    for future in as_completed(futures):27        try:28            url, size = future.result()29            print(f"{url}: {size:,} bytes")30        except requests.RequestException as exc:31            print("failed:", exc)32 33print(f"total: {total_bytes:,} bytes")

1/4A shared counter and the Lock that protects it.

Four pages fetched at the same time with a thread pool. Needs pip install requests.

Save yourself the pain

Common mistakes

Oops

Never calling future.result(), so errors in threads disappear silently.

Do this instead

Always collect results. An exception raised in a worker only shows up when you call result().

Oops

Using max_workers=500 to go faster.

Do this instead

Too many threads waste memory and can get you rate-limited. Start with 5 to 20 for network jobs and measure.

Oops

Updating a shared list or counter from threads without a lock.

Do this instead

Use threading.Lock, or avoid shared state by returning results and combining them in the main thread.

Your mission

Website health checker

~30 min

Quick check

What is the main difference between pool.map() and as_completed()?

Go deeper

  1. 1Download several web pages at once with ThreadPoolExecutor.map.
  2. 2Create a race condition on a shared counter, then fix it with a Lock.
  3. 3Use as_completed to process results as soon as each finishes.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge