Threads
Threads let one Python program wait on many slow things at once, such as web requests or file downloads. The easiest and safest way is concurrent.futures.ThreadPoolExecutor: give it a function and a list of inputs, and it runs them across a pool of threads. Protect shared data with a Lock, or avoid sharing by returning results.
The problem: waiting in a row
import time
def fetch(url: str) -> str:
time.sleep(1) # pretend network delay
return f"data from {url}"
urls = ["a.com", "b.com", "c.com"]
start = time.perf_counter()
results = [fetch(u) for u in urls]
print(results)
print(f"{time.perf_counter() - start:.1f}s")['data from a.com', 'data from b.com', 'data from c.com'] 3.0s
ThreadPoolExecutor
import time
from concurrent.futures import ThreadPoolExecutor
def fetch(url: str) -> str:
time.sleep(1)
return f"data from {url}"
urls = ["a.com", "b.com", "c.com"]
start = time.perf_counter()
with ThreadPoolExecutor(max_workers=5) as pool:
results = list(pool.map(fetch, urls))
print(results)
print(f"{time.perf_counter() - start:.1f}s")['data from a.com', 'data from b.com', 'data from c.com'] 1.0s
pool.map(fetch, urls)runsfetchfor every URL and returns results in the original order.max_workerslimits how many run at once — be polite to servers and stay within rate limits.- The
withblock waits for all threads to finish before continuing.
Handling results as they finish
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
def download(name: str, seconds: float) -> str:
time.sleep(seconds)
if name == "broken.zip":
raise ConnectionError("server error")
return name
jobs = {"big.iso": 0.6, "small.txt": 0.1, "broken.zip": 0.3}
with ThreadPoolExecutor() as pool:
futures = {pool.submit(download, n, s): n for n, s in jobs.items()}
for future in as_completed(futures):
name = futures[future]
try:
print("done:", future.result())
except ConnectionError as err:
print(f"failed: {name} ({err})")done: small.txt failed: broken.zip (server error) done: big.iso
submit returns a Future — a placeholder for a result that isn't ready yet. as_completed yields futures in the order they finish, and future.result() re-raises any error from the thread so you can handle it.
Shared data needs a Lock
import threading
from concurrent.futures import ThreadPoolExecutor
counter = 0
lock = threading.Lock()
def add_many(n: int) -> None:
global counter
for _ in range(n):
with lock: # only one thread at a time in here
counter += 1
with ThreadPoolExecutor(max_workers=4) as pool:
for _ in range(4):
pool.submit(add_many, 100_000)
print(counter)400000
Producer and consumer with Queue
import queue
import threading
tasks: queue.Queue[str | None] = queue.Queue()
def worker() -> None:
while (item := tasks.get()) is not None:
print("processing", item)
t = threading.Thread(target=worker)
t.start()
for item in ["invoice-1", "invoice-2"]:
tasks.put(item)
tasks.put(None) # signal: no more work
t.join()
print("all done")processing invoice-1 processing invoice-2 all done
Practice
Plan a thread pool. Write batches(items, size) that splits a list into lists of at most size items (the way a pool hands work to workers). Print batches(list(range(7)), 3) and then how many batches 100 URLs make with size=8.
[[0, 1, 2], [3, 4, 5], [6]] 13