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
- Sub-topics 1-2 are the entry point: what a thread actually is, the I/O-bound vs. CPU-bound distinction that decides whether threading even helps, and the raw mechanics of
threading.Thread,.start(),.join(). - Sub-topic 3 is the honest caveat: the GIL (Global Interpreter Lock) — why Python threads speed up waiting but not crunching numbers.
- Sub-topics 4-5 are the real danger and its fix: race conditions from shared mutable state, and
threading.Lockto prevent them. - Sub-topic 6 is a broader habit: structuring code to avoid sharing mutable state in the first place, which avoids needing a lock at all.
- Sub-topic 7 is the modern, higher-level tool:
concurrent.futures.ThreadPoolExecutor, which most real code reaches for instead of rawThreadobjects. - Sub-topic 8 ties it together with the real-world cases threading actually shows up in — concurrent downloads, concurrent API calls (ties back to Chapter 19), and parallel file processing.
- Every timing example uses
time.sleep()to stand in for a slow network or disk operation. No example makes a real network call or writes a real file — this chapter simulates exactly the kind of waiting threading is built for, so every example runs identically and safely for every learner, every time. - Thread execution order can vary between runs — the chapter is built around that. Every graded example is deliberately designed so the final result is the same no matter which thread happens to run first.
1. What a thread is, and why it helps
- 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).
Not every kind of work benefits from more threads. The distinction that decides it:
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.
- Threading helps when a program spends time waiting — downloads, API calls (Chapter 19), database queries, reading many files.
- Threading does not help pure number-crunching in Python — more threads doesn't make one CPU compute any faster.
- This chapter's examples use
time.sleep()to simulate a wait, since it behaves exactly like waiting on the network without needing a real, possibly-flaky network call.
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?"
- 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.
2. Creating and starting threads
threading.Thread(target=function, args=(...))creates a thread that will runfunctionwhen started..start()actually begins running the thread, alongside the main program..join()pauses the calling code until that thread has finished.
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:
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")
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:
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.
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")
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.
.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.
threading.Thread(target=fn, args=(...))creates a thread; it hasn't started running yet..start()begins running the thread; calling.start()on several threads before joining any of them is what lets their waits overlap..join()blocks until a specific thread finishes — call it on every thread before trusting their combined results.
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.
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 rawThreadhas no built-in way to return a value, so results are usually collected into a shared list or object instead.
3. The GIL
- 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.
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.
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.
- The GIL means only one thread runs Python bytecode at a time, even with multiple CPU cores.
- A thread waiting on I/O releases the GIL for that wait, which is exactly what lets other threads run concurrently during it.
- A thread doing pure computation holds the GIL almost continuously, so more threads doing CPU-bound work don't meaningfully speed anything up.
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.
- 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.
4. Race conditions
- 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 += 1is 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.
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:
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)")
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.
- A race condition needs shared, mutable state that more than one thread both reads and writes.
- An operation that looks like one line in Python source code can still be several separate steps underneath — a gap between any of those steps is where a race condition can slip in.
- The GIL prevents two threads from running Python bytecode at the literal same instant, but does not prevent this kind of interleaving between separate operations — it does not make Python threading automatically thread-safe.
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."
- A race condition happens when multiple threads read and write shared mutable state without coordination.
- Even a simple-looking update like
counter += 1is 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.
5. threading.Lock
- 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.
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)")
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.
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.
threading.Lock()creates a lock; only one thread can hold it at a time.with lock:is the standard way to use one — it acquires the lock, runs the block, and always releases it afterward.- Only the code that actually touches shared, mutable state needs to be inside the lock — locking more than necessary just makes threads wait on each other for no benefit.
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.
- 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 athreading.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.
6. Thread safety patterns
- 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.
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:
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}")
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.
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.
- Structuring code so each thread only touches its own local data avoids race conditions without needing a lock at all.
- Combine results only after every thread has finished (after every
.join()), never while threads are still running. threading.local()is the standard tool when a shared object genuinely needs to exist, but each thread should see its own private version of specific values on it.
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.
- 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.
7. concurrent.futures.ThreadPoolExecutor
ThreadPoolExecutormanages a fixed pool of worker threads automatically — no manualThread()/.start()/.join()bookkeeping..map(function, items)runsfunctionacross every item initemsconcurrently and returns results in the original order..submit(function, *args)plusas_completed()is used when results are needed as soon as each one finishes, in whatever order that happens to be.
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.
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:
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)
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:
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.
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)
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.
ThreadPoolExecutor(max_workers=N)manages a pool ofNworker threads automatically..map(fn, items)is the simplest option: results come back as a list, in input order..submit(fn, *args)returns aFutureimmediately;as_completed()yields each one as its task finishes, in completion order rather than submission order.
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.
ThreadPoolExecutormanages a pool of worker threads, removing manualThread/.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.
8. Real-world threading
- 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
ThreadPoolExecutoralternative.
Three shapes of real work show up constantly, and all three are exactly Sub-topic 1's I/O-bound case:
- Concurrent downloads: pulling multiple files from a server (or multiple servers) at once, rather than one at a time — this chapter's project builds exactly this, simulated with
time.sleep(). - Concurrent API calls: Chapter 19's
requests.get()pattern, called several times for different resources at once instead of sequentially — checking the weather for five cities concurrently instead of one after another, for instance. - Parallel file processing: reading and processing several independent files (Chapter 13's file handling) at the same time, when each file's processing spends real time waiting on disk I/O.
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.
- 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 aThreadPoolExecutoralternative into one tool.
- Web browsers, download managers, and any app with a "loading several things at once" screen rely on threading (or an equivalent concurrency tool) to overlap waits instead of doing them one at a time.
- Race conditions are a real, expensive category of production bug specifically because they're timing-dependent — code can pass every test during development and still fail unpredictably under real concurrent load, which is exactly why defensive locking or shared-nothing design (Sub-topics 5-6) matters more here than in most other chapters.
ThreadPoolExecutor(or an equivalent thread-pool abstraction) is the default choice in most production Python code that needs concurrency for I/O-bound work — rawThreadobjects are still worth understanding, but real code rarely manages them by hand once a pool-based tool is available.
Points to Remember
- A thread is a separate line of execution sharing a program's memory; threading speeds up I/O-bound work (waiting on network, disk, a database) but not CPU-bound work (pure computation).
threading.Thread(target=fn, args=(...))creates a thread;.start()begins it;.join()waits for it to finish. Start every thread before joining any of them to let their waits overlap.- The GIL lets only one thread run Python bytecode at a time, but a thread waiting on I/O releases it, letting other threads run — the reason threading helps I/O-bound work specifically.
- A race condition happens when multiple threads read and write shared mutable state without coordination; the GIL does not prevent this.
with lock:(fromthreading.Lock()) lets only one thread run a block of code at a time, fixing a race condition by closing the gap it depends on.- Avoiding shared mutable state between threads (giving each thread its own data, combining results only after every thread finishes) sidesteps race conditions without needing a lock at all.
concurrent.futures.ThreadPoolExecutormanages a pool of worker threads automatically —.map()for ordered results,.submit()+as_completed()for results as they finish.- Concurrent downloads, concurrent API calls, and parallel file processing are the most common real-world reasons to reach for threading, all of them I/O-bound.