🐍 Python for Everyone

← Back to all chapters

Chapter 20 of 27 Intermediate 80 min read

Multithreading

Every program so far has run one line at a time, from top to bottom. That's fine for pure computation, but a huge amount of real software spends most of its time waiting — for a file to download, a database to respond, an API to answer. Threading lets a program start several of those waits at the same time instead of one after another, which is exactly why a browser can load a dozen images at once instead of one at a time. This chapter builds threading's real mechanics: starting threads, the tradeoff Python's GIL creates, the race conditions that come with sharing data across threads, and the tools — Lock and ThreadPoolExecutor — that keep it safe.

How to read this chapter

Picture downloading three files from the internet, one at a time: each download takes a full second of the program just sitting there waiting for data to arrive over the network, so three files take three seconds total, even though the computer's CPU was doing almost nothing that whole time. Now picture starting all three downloads at once and waiting for them together — the total time is close to whichever single download takes longest, not the sum of all three. That's the entire point of this chapter: letting a program overlap multiple waits instead of doing them one after another.
Sub-topic 1 of 8

1. What a thread is, and why it helps

At a glance
  • A thread is a separate line of execution inside the same running program, able to run alongside other threads.
  • I/O-bound work spends most of its time waiting (network, disk, a database) — threading helps here.
  • CPU-bound work spends most of its time actually computing — threading does not speed this up in Python (Sub-topic 3 explains exactly why).
Why this matters: every other tool in this chapter only matters for the right kind of problem. Using threading on the wrong kind of work (CPU-bound) is a genuinely common mistake, and this distinction is the one thing to get right before writing any threading code at all.
What is... a thread? A thread is a separate line of execution running inside the same program, sharing that program's memory with every other thread it runs alongside. Every Python program already runs on one thread (the "main thread") by default — this chapter is about deliberately starting more of them so a program can do several things at once instead of one after another.

Not every kind of work benefits from more threads. The distinction that decides it:

What is... I/O-bound vs. CPU-bound work? I/O-bound work spends most of its time waiting on something outside the CPU — a network response, a disk read, a database query — the CPU itself is idle during that wait. CPU-bound work spends most of its time actually computing — crunching numbers, running a loop that does real math on every iteration — the CPU is busy the entire time, with nothing to wait on. Downloading a file is I/O-bound; calculating the ten-millionth prime number is CPU-bound.
why overlapping waits helps: 3 downloads, 1 second each
One at a time (sequential):
[--download 1--][--download 2--][--download 3--]
0s              1s              2s              3s

At the same time (threaded):
[--download 1--]
[--download 2--]
[--download 3--]
0s                                                1s

Nothing about the network itself got faster in the threaded version — each individual download still takes a full second. What changed is that all three waits now happen at the same time instead of back to back, so the program's total wall-clock time shrinks toward the length of the single slowest download, rather than the sum of all three. This is the entire payoff threading offers for I/O-bound work, and it's exactly why a real download manager, web browser, or API client uses it.

Go Deeper: what actually helps CPU-bound work, if not threads?

Python's multiprocessing module runs code in separate full processes instead of threads — each process gets its own Python interpreter and its own CPU core to run on, which genuinely speeds up CPU-bound work by spreading the actual computation across multiple cores. It's a heavier tool (each process has its own memory, so sharing data between them is more work than sharing between threads) and outside this chapter's scope, but it's the answer to "what do I use for CPU-bound work instead of threading?"

Quick recap
  • A thread is a separate line of execution inside the same program, sharing its memory with other threads.
  • I/O-bound work (waiting on network, disk, a database) benefits from threading; CPU-bound work (pure computation) does not.
  • Overlapping several waits at once shrinks a program's total time toward the slowest single wait, rather than the sum of every wait.
Sub-topic 2 of 8

2. Creating and starting threads

At a glance
  • threading.Thread(target=function, args=(...)) creates a thread that will run function when started.
  • .start() actually begins running the thread, alongside the main program.
  • .join() pauses the calling code until that thread has finished.
Why this matters: Thread, .start(), and .join() are the three raw building blocks every other tool in this chapter (including ThreadPoolExecutor in Sub-topic 7) is built on top of — understanding them directly is what makes the higher-level tools feel like a shortcut rather than magic.

First, the same download simulation from Sub-topic 1, running one download at a time — no threading yet, just a baseline to compare against:

sequential_download_demo.py
import time

def download_file(name, seconds):
    time.sleep(seconds)  # stands in for time spent waiting on the network
    return f"{name} downloaded"


start = time.time()
results = []
for name, seconds in [("photo.jpg", 1), ("song.mp3", 1), ("video.mp4", 1)]:
    results.append(download_file(name, seconds))
elapsed = time.time() - start

for r in results:
    print(r)
print(f"Sequential total: about {round(elapsed)}s")
actual output of sequential_download_demo.py
photo.jpg downloaded
song.mp3 downloaded
video.mp4 downloaded
Sequential total: about 3s

Three one-second waits, run back to back, take about three seconds total — exactly what's expected with no concurrency at all. Starting a thread for each download instead changes only how the waiting happens, not what each function does:

What is... threading.Thread? threading.Thread(target=some_function, args=(arg1, arg2)) creates a new thread object configured to run some_function with the given arguments once started — creating it doesn't start it running yet, that's what .start() is for.
threaded_download_demo.py
import time
import threading

def download_file_threaded(name, seconds, results_list):
    time.sleep(seconds)
    results_list.append(f"{name} downloaded")


results = []
start = time.time()
threads = []
for name, seconds in [("photo.jpg", 1), ("song.mp3", 1), ("video.mp4", 1)]:
    t = threading.Thread(target=download_file_threaded, args=(name, seconds, results))
    threads.append(t)
    t.start()

for t in threads:
    t.join()
elapsed = time.time() - start

for r in sorted(results):
    print(r)
print(f"Threaded total: about {round(elapsed)}s")
actual output of threaded_download_demo.py
photo.jpg downloaded
song.mp3 downloaded
video.mp4 downloaded
Threaded total: about 1s

All three one-second waits now happen at the same time, so the total time drops to about one second instead of three — the exact speedup Sub-topic 1's diagram predicted. Three things make this work: t.start() is called for every thread before any t.join() is called, so all three downloads actually begin overlapping; each thread appends its own result to a shared results list instead of returning a value directly (an ordinary function's target can't hand a return value back the way a normal function call does); and the results are printed with sorted(), since the order threads finish in isn't guaranteed — sorting first is what makes this example's printed output the same on every run despite that.

What is... .join()? Calling some_thread.join() pauses whichever code called it until some_thread has completely finished running. Without calling .join() on every thread before reading their results, the main program could try to read results before every thread has actually finished appending to it — .join() is what guarantees "wait until this thread is truly done" before moving on.
try_it.py
Click "Run Code" — try adding a fourth task with a different name and duration.
Go Deeper: why append to a shared list instead of returning a value?

A function passed as target= to Thread() does still technically return a value like any function, but nothing in the threading module ever reads that return value back out — there's no built-in thread.result(). The two standard ways to actually get a result out of a raw Thread are appending to a shared list (as this sub-topic's demo does) or storing onto a shared object each thread has a reference to; Sub-topic 7's ThreadPoolExecutor fixes this awkwardness directly, which is one of the real reasons it's the more commonly reached-for tool for new code.

Quick recap
  • threading.Thread(target=fn, args=(...)) creates a thread; .start() begins running it.
  • Starting every thread before joining any of them is what lets their waits happen concurrently.
  • .join() blocks until a thread finishes; a raw Thread has no built-in way to return a value, so results are usually collected into a shared list or object instead.
Sub-topic 3 of 8

3. The GIL

At a glance
  • The GIL (Global Interpreter Lock) allows only one thread at a time to actually execute Python bytecode, even on a multi-core machine.
  • A thread waiting on I/O releases the GIL during that wait, letting another thread run — this is exactly why threading speeds up I/O-bound work.
  • CPU-bound work never gives up the GIL for long, so extra threads doing pure computation don't run any faster in standard Python.
Why this matters: this is one of the most commonly asked Python interview questions, and getting it wrong ("Python threads don't run in parallel, so threading is pointless") throws away a genuinely useful tool for exactly the I/O-bound case this chapter is built around.
What is... the GIL? The Global Interpreter Lock (GIL) is a lock built into the standard Python interpreter (CPython) that only allows one thread to execute Python bytecode at any given instant, no matter how many CPU cores the machine has. It exists to keep Python's internal memory management simple and safe by default — the tradeoff is that multiple Python threads never truly run Python code simultaneously on separate cores.

That sounds like it should make threading useless — and for pure computation, it very nearly does. The detail that changes everything for I/O-bound work: a thread that's waiting on something outside the CPU (a network response, a disk read, time.sleep()) releases the GIL for the duration of that wait, letting a different thread run during it.

the GIL during an I/O wait vs. a CPU-bound loop
I/O-bound (time.sleep, network, disk):
Thread A: [holds GIL, briefly][--- waiting, GIL released ---][holds GIL again]
Thread B:                     [--- runs here, holds GIL ----]

CPU-bound (a tight computation loop):
Thread A: [-------------- holds GIL almost the whole time --------------]
Thread B: [ barely runs at all -- A rarely lets go of the GIL long enough ]

During time.sleep() specifically (and during a real network call or file read), the thread genuinely isn't running any Python bytecode at all — it's just waiting — so releasing the GIL during that wait costs nothing and lets other threads make real progress. A CPU-bound loop, by contrast, is running Python bytecode continuously, so it only gives up the GIL for brief, periodic intervals, leaving little room for another thread to meaningfully progress. This is the entire reason Sub-topic 1's I/O-bound vs. CPU-bound distinction matters as much as it does.

Go Deeper: is the GIL going away?

Recent CPython releases have introduced an experimental "free-threaded" build that can run without the GIL at all, and this is an active area of ongoing work in the Python project. As of this writing it's still opt-in and not yet the default for most production code, so the GIL's behavior described here is still the practical reality for the vast majority of Python programs running today — worth knowing the direction things are heading, but not a reason to skip understanding how the GIL behaves right now.

Quick recap
  • The GIL lets only one thread run Python bytecode at a time, regardless of CPU core count.
  • A thread waiting on I/O releases the GIL during that wait, letting other threads run — the reason threading helps I/O-bound work.
  • A CPU-bound thread rarely releases the GIL, so threading doesn't meaningfully speed up pure computation in standard Python.
Sub-topic 4 of 8

4. Race conditions

At a glance
  • A race condition happens when two threads read and write the same shared value without coordination, and the result depends on unpredictable timing.
  • Even a single line like counter += 1 is really three separate steps under the hood: read, add, write back.
  • If one thread's read/add/write gets interleaved with another thread's, updates can be silently lost.
Why this matters: the GIL (Sub-topic 3) stops two threads from executing Python bytecode at the exact same instant, but it does not stop a thread from being paused mid-operation while another thread runs — and that gap is exactly where race conditions live.
What is... a race condition? A race condition is a bug that happens when the correctness of a program depends on the precise order or timing in which multiple threads happen to run — the code "races" to see which thread's operations interleave with which, and the outcome isn't guaranteed to be the same every time. It's called a shared mutable state problem: it only happens when multiple threads read and write the same value without any coordination.

counter += 1 looks like one atomic step, but it's genuinely three: read the current value of counter, add 1 to it, then write the new value back. If Thread A reads counter, then gets paused before it writes back, and Thread B reads the same (still-old) value and writes its own update, Thread A's eventual write overwrites Thread B's work entirely — one whole increment is silently lost:

race_condition_demo.py
import time
import threading

counter = 0

def increment_unsafe(times):
    global counter
    for _ in range(times):
        current = counter
        time.sleep(0)  # forces a moment where another thread can run
        counter = current + 1


threads = [threading.Thread(target=increment_unsafe, args=(2000,)) for _ in range(4)]
for t in threads:
    t.start()
for t in threads:
    t.join()

print(f"Expected 8000, got {counter} (a lower, inconsistent number -- lost updates)")
actual output of race_condition_demo.py (varies run to run)
Expected 8000, got 2002 (a lower, inconsistent number -- lost updates)

Four threads each increment counter 2000 times, so the correct final total is 4 × 2000 = 8000. The printed number instead comes out lower — and a different, unpredictable amount lower on different runs — because time.sleep(0) deliberately creates a gap between reading current and writing it back, giving another thread the exact opening it needs to read the same stale value first. The specific number is never reliable, but one thing about this example is completely reliable: it never prints the correct 8000, run after run — which is the whole demonstration.

Go Deeper: why don't ordinary programs hit this constantly?

Most day-to-day threaded code either avoids sharing mutable state between threads at all (Sub-topic 6) or already protects the state it does share with a lock (Sub-topic 5) — race conditions show up specifically when a program shares mutable data across threads without either safeguard. They're also notoriously hard to catch by accident during testing, since the bad interleaving needs exact timing to happen — a race condition can pass every test run during development and then fail unpredictably in production under real concurrent load, which is exactly why defensive habits (Sub-topics 5-6) matter more here than "just try running it and see if it breaks."

Quick recap
  • A race condition happens when multiple threads read and write shared mutable state without coordination.
  • Even a simple-looking update like counter += 1 is really several separate steps, and threads can interleave between them.
  • The GIL does not prevent race conditions — it only stops two threads from executing bytecode at the exact same instant, not from interleaving between separate operations.
Sub-topic 5 of 8

5. threading.Lock

At a glance
  • A lock lets only one thread at a time run a specific block of code, forcing every other thread to wait its turn.
  • lock = threading.Lock() creates one; with lock: is the standard way to use it.
  • Wrapping the read-modify-write steps in a lock closes exactly the gap that caused Sub-topic 4's race condition.
Why this matters: Sub-topic 4 showed the problem; this is the direct fix, using the exact same shared counter so the before-and-after contrast is as concrete as possible.
What is... a lock? A lock (also called a mutex, short for "mutual exclusion") is an object that only one thread can hold at a time. Any thread that tries to acquire a lock another thread is already holding simply waits until it's released — this is what turns a block of code from "any thread might interleave here" into "only one thread runs this at a time," closing the exact gap a race condition needs.
lock_demo.py
import time
import threading

counter = 0
lock = threading.Lock()

def increment_safe(times):
    global counter
    for _ in range(times):
        with lock:
            current = counter
            time.sleep(0)
            counter = current + 1


threads = [threading.Thread(target=increment_safe, args=(2000,)) for _ in range(4)]
for t in threads:
    t.start()
for t in threads:
    t.join()

print(f"Expected 8000, got {counter} (always correct, every run)")
actual output of lock_demo.py
Expected 8000, got 8000 (always correct, every run)

The code is identical to Sub-topic 4's race condition demo, with one change: the read-modify-write sequence is now wrapped in with lock:. A thread that reaches with lock: while another thread already holds lock simply waits there until it's released — so the time.sleep(0) gap that used to let another thread sneak in and read a stale value can no longer do any damage, since no other thread can even enter that block while one is inside it. counter now comes out exactly 8000 on every single run, with no exceptions.

What is... with lock:? with lock: acquires lock at the start of the block and automatically releases it at the end — including if an exception happens partway through, which manual lock.acquire()/lock.release() calls would require a try/finally to guarantee safely. This is the exact same context-manager pattern from Chapter 17's with open(...) as f:, just applied to a different kind of resource — a chunk of code that needs exclusive access instead of an open file.
try_it.py
Click "Run Code" — try removing "with lock:" (unindent the two lines inside it) and see the result become unreliable.
Go Deeper: what happens if two threads each wait on a lock the other is holding?

That specific situation — two (or more) threads each waiting on a lock the other one holds, so neither can ever proceed — is called a deadlock, and it's the classic failure mode locks introduce as a tradeoff for the safety they provide. It typically only happens when code needs to hold multiple locks at once in an inconsistent order across different threads; every example in this chapter uses exactly one lock at a time, which avoids the problem entirely, but it's worth knowing the name for when locking gets more advanced.

Quick recap
  • A lock lets only one thread run a given block of code at a time; other threads wait their turn.
  • with lock: acquires and releases a threading.Lock() automatically, including if an exception occurs inside the block.
  • Wrapping shared state's read-modify-write steps in a lock is what actually fixes a race condition, as opposed to just making it less likely.
Sub-topic 6 of 8

6. Thread safety patterns

At a glance
  • The most reliable way to avoid a race condition is to avoid sharing mutable state between threads in the first place.
  • Giving each thread its own separate data to work with, then combining results afterward, sidesteps needing a lock at all.
  • threading.local() gives each thread its own private copy of a value, automatically.
Why this matters: a lock (Sub-topic 5) fixes a race condition, but it also means threads spend time waiting on each other — the fastest, simplest fix is often not needing a lock at all, by structuring the work so nothing is actually shared.

The cleanest thread-safety pattern doesn't add a lock — it removes the reason one was needed. Instead of every thread writing into one shared list or counter, give each thread its own private space to work in, and only combine everything after every thread has finished:

per_thread_results_demo.py
import threading

def count_up_to(n, result_holder):
    total = 0
    for i in range(1, n + 1):
        total += i
    result_holder.append(total)  # each thread only ever appends its OWN total


result_holder = []
threads = [threading.Thread(target=count_up_to, args=(1000, result_holder)) for _ in range(4)]
for t in threads:
    t.start()
for t in threads:
    t.join()

grand_total = sum(result_holder)
print(f"Each thread's total: {sorted(result_holder)}")
print(f"Grand total: {grand_total}")
actual output of per_thread_results_demo.py
Each thread's total: [500500, 500500, 500500, 500500]
Grand total: 2002000

No lock appears anywhere in this example, and it's still completely safe. The key difference from Sub-topic 4's race condition: each thread computes its own independent total (a variable local to that thread's own function call, never touched by any other thread) and only appends once, at the very end. Appending to a Python list is itself a safe, effectively atomic operation for this use case — the actual risk (reading, then later writing back a value based on that read) never happens here at all, because nothing is shared until every thread is completely done computing.

What is... threading.local()? threading.local() creates a special object where each thread automatically gets its own separate copy of whatever attributes are stored on it — Thread A setting data.value = 1 and Thread B setting data.value = 2 on the exact same threading.local() object never collide, since each thread is silently reading and writing its own private copy. It's a more advanced tool than this chapter's examples need (the "give each thread its own local variable and combine results afterward" pattern above covers the same idea more simply), but it's the standard name for this pattern when a library or framework needs many pieces of code to share one object while still keeping each thread's data separate.
Go Deeper: "share nothing" vs. "lock what's shared" — which to reach for?

When the work naturally splits into independent pieces (each thread's job doesn't need to know about any other thread's job until the very end), avoiding shared state entirely is almost always simpler and faster — there's nothing to protect, so there's nothing threads have to wait on each other for. A lock becomes necessary specifically when threads genuinely need to update the same piece of state as they go (a running total that has to stay accurate mid-execution, not just at the end, for instance) — in that case, structuring around shared state isn't optional, and a lock is the correct tool rather than a workaround.

Quick recap
  • Avoiding shared mutable state between threads sidesteps race conditions entirely, without needing a lock.
  • Giving each thread its own local data and combining results only after every thread finishes is the simplest version of this pattern.
  • threading.local() automatically gives each thread its own private copy of an attribute on a shared object.
Sub-topic 7 of 8

7. concurrent.futures.ThreadPoolExecutor

At a glance
  • ThreadPoolExecutor manages a fixed pool of worker threads automatically — no manual Thread()/.start()/.join() bookkeeping.
  • .map(function, items) runs function across every item in items concurrently and returns results in the original order.
  • .submit(function, *args) plus as_completed() is used when results are needed as soon as each one finishes, in whatever order that happens to be.
Why this matters: Sub-topic 2's raw Thread objects work, but they require manually tracking every thread, manually collecting results into a shared list, and manually calling .join() on each one. ThreadPoolExecutor is the modern, higher-level tool that handles all of that, and it's what most real-world threaded code reaches for by default.
What is... a thread pool? A thread pool is a fixed, reusable set of worker threads that a program hands pieces of work to, instead of creating and destroying a brand-new thread for every single task. ThreadPoolExecutor(max_workers=N) creates a pool of N worker threads and takes care of assigning submitted work to whichever worker is free, entirely automatically.

.map() is the simplest entry point — it looks and feels almost exactly like the built-in map() from Chapter 9, just running each call on its own thread from the pool:

thread_pool_map_demo.py
import time
from concurrent.futures import ThreadPoolExecutor

def download_v2(item):
    name, seconds = item
    time.sleep(seconds)
    return f"{name} downloaded"


items = [("photo.jpg", 0.3), ("song.mp3", 0.3), ("video.mp4", 0.3)]
with ThreadPoolExecutor(max_workers=3) as pool:
    results = list(pool.map(download_v2, items))

for r in results:
    print(r)
actual output of thread_pool_map_demo.py
photo.jpg downloaded
song.mp3 downloaded
video.mp4 downloaded

No Thread(), .start(), .join(), or shared results list anywhere in sight — pool.map() hands every item to the pool's workers, waits for all of them, and returns the results as a list in the same order as the input items, regardless of which download actually finished first. That guaranteed ordering is exactly why this example needs no sorted() call the way Sub-topic 2's raw-Thread version did — .map() already handles it. The with ThreadPoolExecutor(...) as pool: line is the same context-manager pattern as with open(...): it automatically shuts down every worker thread in the pool once the block finishes.

When results are needed as soon as each one finishes — not necessarily in the original order — .submit() returns a future for each call, and as_completed() yields each future the moment its task finishes:

What is... a Future? A future is an object representing a result that doesn't exist yet, but will once its underlying task finishes. pool.submit(fn, *args) returns a Future immediately, without waiting for fn to actually run — calling .result() on that future later blocks until the task is done and then returns its actual return value.
thread_pool_submit_demo.py
import time
from concurrent.futures import ThreadPoolExecutor, as_completed

def download_v3(name, seconds):
    time.sleep(seconds)
    return f"{name} downloaded"


items = [("photo.jpg", 0.3), ("song.mp3", 0.3), ("video.mp4", 0.3)]
with ThreadPoolExecutor(max_workers=3) as pool:
    futures = [pool.submit(download_v3, name, seconds) for name, seconds in items]
    completed = []
    for future in as_completed(futures):
        completed.append(future.result())

for r in sorted(completed):
    print(r)
actual output of thread_pool_submit_demo.py
photo.jpg downloaded
song.mp3 downloaded
video.mp4 downloaded

as_completed(futures) yields each future as soon as its task finishes — useful for processing results the moment they're ready rather than waiting for every single one, but it means the completion order isn't guaranteed to match submission order (all three downloads here take the same simulated time, so this example sorts before printing to keep the printed output identical on every run). .map() is simpler and preserves input order automatically; .submit() plus as_completed() is the right tool specifically when a program wants to react to each result as soon as it's available.

try_it.py
Click "Run Code" — try changing max_workers to 1 and notice it still returns the same result, just slower.
Go Deeper: does ThreadPoolExecutor need locks too?

Yes — ThreadPoolExecutor changes how threads are created and managed, not the fact that Python threads share memory. If work submitted to a pool reads and writes the same shared mutable state the way Sub-topic 4's race condition demo did, it needs exactly the same threading.Lock() protection (Sub-topic 5) or shared-nothing structuring (Sub-topic 6) as raw Thread objects would. ThreadPoolExecutor makes starting and managing threads easier; it doesn't make sharing state between them automatically safe.

Quick recap
  • ThreadPoolExecutor manages a pool of worker threads, removing manual Thread/.start()/.join() bookkeeping.
  • .map(fn, items) returns results in input order; .submit() + as_completed() yields results as each one finishes.
  • A thread pool changes how threads are created and managed, not whether shared state still needs a lock or a shared-nothing structure.
Sub-topic 8 of 8

8. Real-world threading

At a glance
  • Concurrent downloads, concurrent API calls, and parallel file processing are the three most common real-world reasons to reach for threading.
  • Chapter 19's API-fetching pattern (fetch → parse → format) is the exact kind of I/O-bound work threading was built for.
  • This chapter's project combines everything: a menu-driven "concurrent download simulator" comparing sequential vs. threaded timing, protected shared progress, and a ThreadPoolExecutor alternative.
Why this matters: every tool in this chapter exists to solve one of a small number of genuinely common real-world problems — seeing them named explicitly is what turns "I learned about threads" into "I know exactly when to reach for one."

Three shapes of real work show up constantly, and all three are exactly Sub-topic 1's I/O-bound case:

What is... connecting this to Chapter 19? Chapter 19's fetch_weather(city) pattern makes one API call and waits for it. A real dashboard checking five cities' weather could call that same function five times, each on its own thread (or through a ThreadPoolExecutor), and the total wait would shrink toward the time of the single slowest API call instead of the sum of all five — the exact same "overlap the waits" idea as this chapter's download examples, applied to API calls instead of file downloads.

This chapter's project brings every piece together: a menu-driven tool that "downloads" several files concurrently (each a time.sleep() standing in for real network time), reports how much faster that was than doing them one at a time, uses a Lock to safely update shared progress as downloads complete, and offers a second implementation of the same idea built on ThreadPoolExecutor instead of raw Thread objects — a direct, hands-on comparison of Sub-topic 2's raw approach against Sub-topic 7's higher-level one.

Go Deeper: how many threads is too many?

More threads doesn't mean unlimited speedup — past a certain point, the overhead of managing many threads (and, for I/O-bound work, limits like how many connections a server or operating system will allow at once) outweighs any further benefit. Real production code usually caps concurrency deliberately (exactly what ThreadPoolExecutor's max_workers argument is for) rather than starting one thread per item unconditionally, especially when the number of items could be very large.

Quick recap
  • Concurrent downloads, concurrent API calls, and parallel file processing are the three most common real-world uses of threading — all I/O-bound.
  • Chapter 19's fetch-parse-format pattern is exactly the kind of work threading speeds up when called multiple times concurrently.
  • This chapter's project combines timing comparisons, a Lock-protected shared progress log, and a ThreadPoolExecutor alternative into one tool.
In the Real World

Points to Remember

← All Chapters Take the Quiz →