threading.Lock Keeps Updates From Colliding

Locking each read-modify-write with `with lock:` makes four threads incrementing a shared counter lose no updates, and the lock releases automatically.

PythonResilience

Code

pythonsnippet
25 lines
import threading

target = 40_000
counter = 0
lock = threading.Lock()


def bump(times: int) -> None:
    global counter
    for _ in range(times):
        # with lock makes the whole read-modify-write exclusive, so no collisions
        with lock:
            counter += 1


threads = [threading.Thread(target=bump, args=(10_000,)) for _ in range(4)]
for t in threads:
    t.start()
for t in threads:
    t.join()

print("expected:", target)
print("counted :", counter)
print("no lost updates:", counter == target)
print("lock free after joins:", not lock.locked())

Output

Captured from a sandboxed run of this snippet in the build pipeline.

expected: 40000
counted : 40000
no lost updates: True
lock free after joins: True

How the snippet works

Structurally, expect the function bump and nothing else.

for _ in range(times) is the loop that carries the per-item work.

What to watch for

  • Nothing third-party is pulled in; the snippet is dependency-free.

Using it

Entry signature: def bump(times: int) -> None

Output lines are prefixed (expected:, counted :, no lost updates:), making each step’s effect easy to spot.

bump is what another module would consume; nothing else here is load-bearing for callers.

Key statements

def bump(times: int) -> None:
    global counter
    for _ in range(times):
        # with lock makes the whole read-modify-write exclusive, so no collisions
        with lock:
            counter += 1

Interactive Tools for This Topic

FAQ

Is there an install step between copy and run?
No. Between copying and running there is nothing left to do. Every import resolves inside the standard library — `threading`. The file defines `bump` at load time.