Make a shared counter safe when several threads increment it concurrently.
Answer
Protect the read-modify-write update with one shared `threading.Lock`, ideally acquired through `with lock:` so release is exception-safe. Every thread that reads or changes the protected counter must follow the same synchronization rule. The GIL is not an application-level lock and should not be used as the correctness argument for compound shared-state operations.
Strong answer includes
- uses one shared Lock
- protects the compound counter update
- does not rely on the GIL for correctness
Practical example
from threading import Lock, Thread
counter = 0
lock = Lock()
def worker():
global counter
for _ in range(5_000):
with lock:
counter += 1
threads = [Thread(target=worker) for _ in range(4)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
print(counter)Every increment is performed while holding the same lock, so the compound update cannot interleave with another protected increment.
Expected result: 20000.