Sub topic 3
Protecting Shared State in Free-Threaded Python
Assume you know threading, concurrent.futures, and basic race conditions. In a free-threaded build, threads can execute Python code at the same time. The GIL no longer protects a read-modify-write sequence.
Locks and safer designs
A lock is a synchronization object that lets only one thread enter a protected section at a time.
import threading
counter = 0
lock = threading.Lock()
def add_items(amount):
global counter
for _ in range(amount):
with lock:
counter += 1
threads = [threading.Thread(target=add_items, args=(10_000,))
for _ in range(4)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
print(counter) # 40000counter += 1 reads, changes, and writes a value. It is not one atomic operation. Without the lock, updates can be lost.
Prefer queue.Queue for producer-consumer work. Use thread-local storage when each thread needs private state. Immutable values, such as tuples, reduce synchronization because threads cannot change them.
C extensions and interpreter internals
A C extension must declare that it supports the free-threaded ABI. If an imported extension is not marked as compatible, CPython can re-enable the GIL to protect that extension. Check dependency documentation and test the actual interpreter you deploy.
Free-threading changes reference counting and memory allocation. CPython uses deferred or biased reference counting, immortal objects for frequently shared objects, and allocator changes that allow safer concurrent memory management. These changes remove the need for one global lock, but they add coordination costs.
Performance and migration
Free-threaded threads can speed up pure-Python CPU work, but synchronization and memory overhead can reduce or erase the gain. Multiprocessing still provides strong isolation and can be better for workloads with incompatible extensions. Threads remain convenient for shared-memory work and I/O.
Test with the free-threaded interpreter, run race-focused tests repeatedly, inspect dependencies, and measure real workloads. Do not treat passing tests under the GIL as proof of thread safety.
Exercise
Why does with lock: counter += 1 protect the counter?
Show answer
The lock allows only one thread at a time to perform the complete read-modify-write operation.