Skip to content
IT Vizag
← Async & Performance

▶ 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

Lesson 5 of 10 · 2 min read

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

🔒 Code example: sign up free (above) to unlock it.

The thread pool version

🔒 Code example: sign up free (above) to unlock it.

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

🔒 Code example: sign up free (above) to unlock it.

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:

🔒 Code example: sign up free (above) to unlock it.

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).

Tip: concurrent.futures has the same interface for threads and processes. Switching from ThreadPoolExecutor to ProcessPoolExecutor is often a one-word change.

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.

Saved on this device. Sign in to keep progress everywhere.

Share with a friend