Control the interleaving instead of waiting for luck
Two increments from an initial shared counter of zero should produce two. But a read, a calculation, and a write are not automatically one indivisible application operation. Both workers can read zero and later write one. One requested update then disappears from the final result.
The example uses a barrier so that both workers finish reading before either proceeds to write. It does not rely on a chosen sleep duration or the hope that the scheduler exposes a race. The resulting value can be explained from the deliberately constructed ordering of reads and writes.
Run and compare the two cases
In the first case, each worker saves the shared value in its own old variable, waits at the barrier, and writes old+1. In the second case, the same Lock surrounds both reading and writing. Joining both threads before checking the result distinguishes a lost update from simply checking while work remains unfinished.
The barrier has a finite timeout. Under ordinary successful execution, the forced interleaving produces one and the protected case produces two. Thread-start failures or environment problems are different faults. The experiment does not claim that every unprotected increment in every program must produce the same outcome on every run.
import threading
counter = [0]
barrier = threading.Barrier(2, timeout=2)
def lose_update():
old = counter[0]
barrier.wait()
counter[0] = old + 1
threads = [threading.Thread(target=lose_update) for _ in range(2)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
assert counter[0] == 1
print("Forced interleaving:", counter[0])
counter[0] = 0
lock = threading.Lock()
def protected_update():
with lock:
old = counter[0]
counter[0] = old + 1
threads = [threading.Thread(target=protected_update) for _ in range(2)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
assert counter[0] == 2
print("Protected updates:", counter[0])
Protect an invariant, not just one statement
Locking only the write is insufficient if both workers already captured the same old value. The critical section must cover the shared read, the decision based on it, and the write that applies that decision. Derive this boundary from the invariant the application must preserve.
All access paths to the same protected state must follow the same agreement. A locked function cannot establish the intended guarantee if another path modifies the value without coordination. A barrier also serves a different purpose from a mutex: here it aligns progress to expose the problem rather than excluding overlapping updates.
Do not use GIL assumptions as an application contract
The code does not require a thread switch halfway through a single expression. It places the read and write in separate statements with a barrier between them. Neither an implementation detail nor the presence of a GIL should be treated as a promise that an entire application read-modify-write sequence is indivisible.
Locks constrain execution order but can add waiting. Large critical sections and inconsistent acquisition orders can create new problems, including deadlock. Define the necessary correctness boundary and avoid holding it longer than required. This small correctness demonstration does not measure service throughput or establish a performance improvement ratio.