Sub topic 10
Designing for thread safety: queues, thread-local and immutable data
This chapter assumes you can write threaded code with threading or concurrent.futures. It also assumes you know what a race condition is and how threading.Lock works. The previous chapter showed how to protect shared state with locks. Here you will learn to design programs so that less state is shared at all.
Why design beats locking
On a free-threaded build, threads run bytecode at the same time on different cores. A lock fixes a race, but every lock is also a place where threads wait. Locks are easy to forget, easy to hold for too long, and they can deadlock when two threads take them in opposite orders.
Three designs avoid most of these problems:
- Message passing. Threads hand data to each other through a queue instead of reading the same variables.
- Thread-local data. Each thread works on its own copy, so nothing is shared.
- Immutable data. Shared objects never change after creation, so concurrent reads are always safe.
These designs also work on a standard GIL build. Code written this way needs no changes when you switch builds.
Pattern 1: hand work over with a queue
queue.Queue is a thread-safe FIFO queue. It does its own locking internally, so put() and get() can be called from any number of threads. A worker that calls get() on an empty queue blocks until something arrives, and no thread polls or spins.
The common structure is producer and consumer. Producers put tasks on one queue. Workers take tasks, compute, and put results on another queue. Only one thread at a time owns any given item.
import queue
import threading
NUM_WORKERS = 4
tasks = queue.Queue()
results = queue.Queue()
def worker():
while True:
item = tasks.get()
if item is None: # sentinel: no more work
break
results.put((item, item * item))
threads = [threading.Thread(target=worker) for _ in range(NUM_WORKERS)]
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()
collected = []
while True:
try:
collected.append(results.get_nowait())
except queue.Empty:
break
print(sorted(collected))Details that matter:
- One sentinel per worker. A worker that reads a sentinel exits and does not pass it on. If you send fewer sentinels than workers, the remaining workers block forever.
- Order of results is not guaranteed. Workers finish in any order, so sort the results or tag each one with its input, as the code does here.
- Bounded queues give backpressure.
queue.Queue(maxsize=100)makesput()block when the queue is full. A fast producer then cannot fill memory while slow workers fall behind. qsize()andempty()are only hints. Another thread can change the queue right after you call them. Use them for logging or after all workers have been joined, as above. Do not use them to decide whether a laterget()will succeed.- Shutdown. For long-running services, use
task_done()andjoin()on the queue, orqueue.shutdown()in Python 3.13 and later, so workers stop cleanly.
Queues move the ownership of an object, but they do not make the object itself thread-safe. If you put a mutable list on a queue and keep using it in the producer, two threads now share it. Treat an object as given away once you have queued it.
ThreadPoolExecutor is a ready-made version of this pattern. Its submit() and map() calls feed an internal queue and return the results through Future objects. Prefer it unless you need long-lived workers or several pipeline stages.
Pattern 2: keep state per thread
threading.local() creates an object whose attributes are separate in every thread. Setting local.x = 1 in one thread does not change what another thread sees at local.x.
This is useful for resources that are not safe to share or are slow to create. Examples are database connections, parsers, buffers, and random number generators. The example below gives each thread its own random.Random, so threads do not contend over one generator's state.
import random
import threading
from concurrent.futures import ThreadPoolExecutor
_local = threading.local()
def get_rng():
rng = getattr(_local, "rng", None)
if rng is None:
rng = _local.rng = random.Random()
return rng
def count_inside(samples):
rng = get_rng()
inside = 0
for _ in range(samples):
x, y = rng.random(), rng.random()
if x * x + y * y <= 1.0:
inside += 1
return inside
if __name__ == "__main__":
per_task = 500_000
with ThreadPoolExecutor(max_workers=4) as pool:
counts = list(pool.map(count_inside, [per_task] * 4))
print("pi is about", 4 * sum(counts) / (4 * per_task))The same example shows a second idea: accumulate privately, merge once. Each task counts into a local variable and returns it. The main thread adds the four numbers after the tasks are done. No shared counter is updated inside the loop, so no lock is needed. This is usually faster than the locked counter from the previous chapter, which makes every thread wait for every increment.
Thread-local data has limits:
- Each thread initializes its own copy, so the first call in each thread pays the setup cost. Create the value lazily, as
get_rng()does. - Thread-local values live as long as the thread. In a pool of long-lived threads, a large per-thread cache stays in memory.
- The values are invisible to other threads. If you need a combined result, you must still return or queue the partial values.
- Thread-local state does not carry over to
asynciotasks, which can share one thread. Usecontextvarsthere.
Pattern 3: share data that cannot change
If no thread can modify an object, no thread can see it half-updated. Immutable objects therefore need no locks, however many threads read them. Built-in immutable types are int, float, str, bytes, tuple, frozenset and None. For your own types, use @dataclass(frozen=True) or typing.NamedTuple.
To change shared configuration, build a new object and replace the reference. Readers copy the reference into a local variable once and use that snapshot.
import threading
from dataclasses import dataclass, replace
@dataclass(frozen=True)
class Settings:
timeout: float
retries: int
hosts: tuple[str, ...]
current = Settings(timeout=5.0, retries=3, hosts=("a.example", "b.example"))
update_lock = threading.Lock()
def reload_timeout(new_timeout):
global current
with update_lock: # serialize writers that derive from the old value
current = replace(current, timeout=new_timeout)
def handle_request():
snapshot = current # one read; the snapshot cannot change
return snapshot.timeout * snapshot.retries
reload_timeout(10.0)
print(handle_request()) # 30.0Reading current once is the important step. A reader that uses current.timeout and current.retries in two separate reads could see values from two different versions if a writer swaps the object in between. With a snapshot, the pair is always consistent.
The lock in reload_timeout is still needed. The line current = replace(current, ...) reads the old value and then writes a new one. Two writers could both derive from the same old object, and one update would be lost. Immutability protects readers. It does not remove the need to coordinate writers.
Watch for these gaps:
- Frozen is shallow. A frozen dataclass that holds a
listordictis not deeply immutable, because the list can still be changed. Use tuples and frozensets inside frozen objects. MappingProxyTypeis only a read-only view. The dictionary underneath can still change if someone holds a reference to it.- Copying costs memory and time. Rebuilding a large structure on every update is wasteful. Immutable snapshots suit data that is read often and changed rarely.
Choosing a pattern
| Situation | Pattern | Main cost |
|---|---|---|
| Work items flow from producers to workers | `queue.Queue` | Items must not be shared after queuing |
| Each thread needs its own scratch resource | `threading.local` | Per-thread setup and memory |
| Many threads read, few write | Frozen objects, swapped by reference | Copy on every change |
| Many threads update one counter or table | Lock, or per-thread totals merged at the end | Contention, or merge code |
Common errors
- Sharing a mutable object after queuing it. The consumer and the producer now both mutate it. Queue a copy, or stop touching it.
- Forgetting sentinels or using
empty()to stop workers. Both cause hangs or lost items. Use one sentinel per worker or the queue's shutdown support. - Storing results in a shared list from inside workers.
list.appendis safe on a free-threaded build, but the order of the results is random and a later read-modify-write on the list is not atomic. Return values from tasks instead. - Mistaking
threading.localfor a cache shared by all threads. Each thread has its own empty copy at first. - Believing "immutable" covers everything inside. Check every field, not just the outer object.
Exercise
A worker pool has 6 threads that read from a queue.Queue until they see None. The producer puts the tasks on the queue, then puts a single None, then calls join() on every thread. What happens, and how do you fix it?
Show answer
One worker reads the None and exits. It does not put the sentinel back, so the other five workers block forever on get() and the join() calls hang. Put one None on the queue for each worker, which here means six, or use the queue's shutdown support.
Exercise
A frozen dataclass has a field tags: list[str]. Is it safe to share one instance among many threads that only read it? What would you change?
Show answer
Not guaranteed. frozen=True stops reassigning the tags attribute, but the list itself can still be changed by any thread that holds the instance, and concurrent mutation is a data race. Make the field tuple[str, ...] and build it from the list when creating the object, so nothing can change it.