Sub topic 10
Designing for thread safety: queues, thread-local and immutable data
This chapter assumes you know the threading module, have read the earlier chapters on data races, and can protect shared state with a Lock. Locks work, but they are easy to forget and easy to get wrong. A better approach is to design programs so threads share little mutable state in the first place.
Prefer not sharing mutable state
On a free-threaded build, threads run bytecode at the same time. Every piece of mutable data that two threads can reach is a possible data race. You have three main ways to shrink that set:
- Pass work between threads through a queue, so one thread owns each item at a time.
- Give each thread its own copy of state with thread-local data.
- Share only data that cannot change.
Queues: hand off ownership
queue.Queue is thread-safe. It uses its own internal locking, so you can call put() and get() from many threads without extra locks. The pattern is simple: producers put items on the queue, workers take them off, and each item is handled by exactly one worker.
import queue
import threading
def worker(tasks, results):
while True:
n = tasks.get()
if n is None: # sentinel: no more work
tasks.task_done()
break
results.put((n, n * n))
tasks.task_done()
tasks = queue.Queue()
results = queue.Queue()
threads = [threading.Thread(target=worker, args=(tasks, results)) for _ in range(4)]
for t in threads:
t.start()
for n in range(10):
tasks.put(n)
for _ in threads:
tasks.put(None) # one sentinel per worker
for t in threads:
t.join()
while not results.empty():
print(results.get())The workers never touch a shared counter or list. Each number moves from the main thread to one worker, and each result moves back. Once an item is on the queue, the sender should stop modifying it. That rule is what keeps the design safe.
Thread-local data: one copy per thread
threading.local() gives each thread its own attributes. Use it for per-thread resources such as database connections, random number generators, or scratch buffers.
import threading
import random
local = threading.local()
def get_rng():
if not hasattr(local, "rng"):
local.rng = random.Random()
return local.rng
def work(name):
rng = get_rng()
print(name, rng.random())
threads = [threading.Thread(target=work, args=(f"t{i}",)) for i in range(3)]
for t in threads:
t.start()
for t in threads:
t.join()Each thread builds its own Random object on first use, so no two threads ever mutate the same generator. The cost is memory, since you hold one copy per thread. Also, thread-local values do not flow back to other threads. You still need a queue or a lock to combine results.
Immutable data: share freely
Data that never changes cannot race. Strings, numbers, tuples of immutable values, frozenset, and frozen dataclasses are safe to read from any number of threads.
from dataclasses import dataclass
@dataclass(frozen=True)
class Config:
host: str
port: int
tags: tuple = ()
config = Config("localhost", 8080, ("a", "b"))To "change" a frozen object, build a new one with dataclasses.replace(config, port=9090), then hand the new object to other threads. Beware of shallow immutability: a frozen dataclass that holds a list is not safe, because the list can still change.
Choosing a pattern
| Situation | Pattern |
|---|---|
| Distributing tasks to workers | `queue.Queue` |
| Per-thread connection or buffer | `threading.local()` |
| Read-mostly settings or lookup data | Frozen dataclass, tuple, `frozenset` |
| Shared counter or cache updated by many threads | A `Lock`, as in the previous chapter |
Common mistakes
- Putting a mutable object on a queue and then modifying it from the sender.
- Using
queue.Queue.empty()to decide whether to stop workers. Another thread may add an item right after the check. Use sentinels instead. - Storing a mutable object inside a frozen dataclass and assuming it is safe.
- Expecting
threading.local()values to be visible in other threads.
Exercise
A frozen dataclass holds a field items: list. Two threads read it while a third calls config.items.append(1). Is the design thread-safe, and how would you fix it?
Show answer
It is not safe. frozen=True only blocks reassigning the field, not changing the list it points to. Store a tuple instead, and build a new object with dataclasses.replace when the data must change.
Exercise
Why does the queue example send one None per worker rather than a single None?
Show answer
Each worker stops after it reads one None. A single sentinel would stop only one worker, and the others would block forever on get().