Python · Chapter 19 of 21
Python threading: locks, queues and ThreadPoolExecutor
15 min study · Examples checked with Python 3.14 and 3.15 ·
A program that downloads twenty files one after another spends most of its time waiting for the network. Concurrency lets those waits overlap. Python offers three ways to do that, and this chapter starts by telling them apart before covering the first one, threads, in detail: starting them, protecting shared data with locks, passing work through queues, and the thread pool that you will use most of the time.
Threads, processes or asyncio?
| Tool | Runs | Best for |
|---|---|---|
Threads (threading, ThreadPoolExecutor) |
Several flows of control in one process, sharing memory | Waiting on I/O with ordinary blocking libraries: files, HTTP clients, databases |
Processes (multiprocessing, ProcessPoolExecutor) |
Separate Python interpreters, each with its own memory | CPU-heavy work such as parsing, image processing, number crunching (chapter 20) |
asyncio (async/await) |
Many tasks taking turns in one thread | Thousands of concurrent network connections with async libraries (chapter 21) |
The deciding question is what the work waits on. Waiting for I/O suits threads or asyncio. Waiting for the CPU suits processes, at least on the standard Python build, for reasons explained at the end of this chapter.
Start and join threads
import threading
import time
def download(name: str, seconds: float) -> None:
time.sleep(seconds) # stands in for a network call
print(f"{threading.current_thread().name} got {name}")
start = time.perf_counter()
threads = [
threading.Thread(target=download, args=(f"file{i}", 0.2), name=f"worker-{i}")
for i in range(3)
]
for t in threads:
t.start()
for t in threads:
t.join()
print(f"all done in {time.perf_counter() - start:.1f}s") # about 0.2s, not 0.6s
target is the function to run; pass it without parentheses, with its arguments in args. start() begins running it in a new thread and returns immediately. join() waits until a thread has finished. Start them all before joining any, otherwise each one finishes before the next begins and nothing overlaps. The three “got” lines can appear in any order: the operating system decides which thread runs when.
A thread object can only be started once. A daemon thread (daemon=True) doesn’t keep the program alive and is killed abruptly at exit, so never give it work that must finish, such as saving a file.
Race conditions and locks
Threads share variables, and that is both their convenience and their danger. counter += 1 looks like one step but is really three: read the value, add one, write it back. If two threads interleave those steps, one update is lost. Such bugs are called race conditions, and they may appear only once in a thousand runs.
import threading
balance = 100
lock = threading.Lock()
def withdraw(amount: int) -> bool:
global balance
with lock: # check and update as one unit
if balance < amount:
return False
balance -= amount
return True
results = []
threads = [threading.Thread(target=lambda: results.append(withdraw(30))) for _ in range(5)]
for t in threads:
t.start()
for t in threads:
t.join()
print(sorted(results), balance) # [False, False, True, True, True] 10
The lock makes the check (“is there enough money?”) and the update happen as one unit: while one thread holds it, others wait at with lock. Without the lock, two threads could both see 40, both withdraw 30, and leave -20. Protect the whole rule, not just individual reads and writes. Keep locked sections short, never sleep or make network calls while holding a lock, and when you need two locks, always take them in the same order; otherwise two threads can each hold one and wait forever for the other, a deadlock.
Pass work through a queue
Instead of sharing variables, threads can hand data to each other through a queue.Queue, which does its own locking:
import queue
import threading
jobs: queue.Queue[int | None] = queue.Queue()
results: queue.Queue[int] = queue.Queue()
def worker() -> None:
while (item := jobs.get()) is not None:
results.put(item * item)
print("worker stopping")
pool = [threading.Thread(target=worker) for _ in range(2)]
for t in pool:
t.start()
for n in range(1, 6):
jobs.put(n)
for _ in pool:
jobs.put(None) # one stop signal per worker
for t in pool:
t.join()
print(sorted(results.get() for _ in range(results.qsize()))) # [1, 4, 9, 16, 25]
get() blocks until an item is available, so idle workers wait without using CPU. None is the stop signal here, and each worker needs its own. This producer-consumer pattern scales from a script to a web crawler. If a worker can fail, catch the exception and report it through the results queue, or the producer never learns about it. For a stop signal that does not travel through the queue, threading.Event gives every thread a flag to check (stop.is_set()) and to wait on.
Use a thread pool for independent tasks
Creating threads by hand is rarely necessary. concurrent.futures.ThreadPoolExecutor keeps a fixed number of worker threads, hands them tasks and returns their results:
from concurrent.futures import ThreadPoolExecutor, as_completed
import time
def fetch(lesson_id: int) -> str:
time.sleep(0.1)
if lesson_id == 3:
raise ValueError(f"lesson {lesson_id} not found")
return f"Lesson {lesson_id}"
with ThreadPoolExecutor(max_workers=4) as pool:
print(list(pool.map(fetch, [1, 2]))) # ['Lesson 1', 'Lesson 2']
futures = {pool.submit(fetch, i): i for i in [1, 2, 3, 4]}
for future in as_completed(futures):
try:
print(futures[future], future.result())
except ValueError as error:
print(futures[future], "failed:", error)
map returns results in input order. submit returns a Future, a placeholder for a result that arrives later; as_completed yields futures as they finish, and future.result() returns the value or re-raises the exception from the worker thread, so failures are not lost. The with block waits for all tasks before continuing. More workers is not always faster: servers rate-limit you, and each thread costs memory. A future cannot interrupt a call that is already running, so give network calls their own timeouts.
The GIL and free-threaded Python
The standard CPython interpreter has a global interpreter lock (GIL): only one thread executes Python bytecode at any moment. Threads still overlap waiting, because blocking calls such as sleep, file reads and socket operations release the GIL, and so do many C extensions like NumPy while they compute. But two threads doing pure-Python arithmetic take turns rather than running in parallel, which is why CPU-heavy work goes to processes.
Since Python 3.13 there is also a free-threaded build without the GIL (often installed as python3.14t), officially supported from 3.14. There, threads can run Python code on several cores at once, provided the extension modules you use support it. sys._is_gil_enabled() tells you which mode you are in. Neither build makes your own data safe: the GIL never protected multi-step updates like the withdrawal above, and a free-threaded build exposes races even more readily. Use locks or queues in both.
Practice
Simulate downloading ten lessons with a ThreadPoolExecutor of three workers, where each download sleeps 0.1 seconds and lesson 7 raises ConnectionError. Print a summary of successes and failures with the lesson IDs, and measure the total time.
Answer check: with three workers, ten 0.1-second tasks take about 0.4 seconds (four rounds), not 1 second. Using submit with a dictionary from future to ID, or map inside a try, the failure for lesson 7 is reported while the other nine succeed. With pool.map, the exception is raised when its result is reached, which stops the loop, so submit with as_completed suits “report every failure” better.
Summary
Use threads for I/O-bound work with blocking libraries, processes for CPU-bound work, and asyncio for very many network tasks. Start all threads before joining them, guard every multi-step rule on shared data with a lock, prefer queues to shared variables, and use ThreadPoolExecutor with futures so results and exceptions come back to you. The GIL limits parallel Python code but never replaces locks.