▶ Sign up free for the video, slides & prompts
The lesson below is open to all. Enter your email once to unlock every video, slide deck, prompt and code example on this device.
Checking…
Threads
Do many network calls at once with concurrent.futures.
🎬 Video version coming soon — read it now
For I/O-bound work, like downloading pages or calling APIs, threads let your program wait for many things at once. While one thread waits for the network, others run.
The slow, one-at-a-time version
The thread pool version
ThreadPoolExecutor keeps up to 10 threads busy, handing each a URL as it becomes free. pool.map returns results in the same order as the inputs.
Handling results as they finish
A future is a placeholder for a result that isn't ready yet. as_completed hands you each one as soon as it's done, and .result() re-raises any exception from that thread so you can handle it.
Shared data needs care
Threads share memory. If two threads update the same variable at once, updates can be lost:
Better still, avoid shared state: have each thread return its result and combine them afterwards, as pool.map does.
How many workers?
- For network calls: 5–50 is typical. Too many can overload the server or hit rate limits.
- Respect the website or API you're calling. Hammering a small site with 100 parallel requests is rude and may get you blocked.
Threads don't speed up pure-Python maths
Because of the GIL, CPU-heavy Python code in threads still runs one thread at a time. For that, use processes (next lesson).
In one line
Use ThreadPoolExecutor to run many I/O waits at once; collect returned results instead of sharing variables, and keep the worker count polite.
Share with a friend