progress

~/problems / Locks / Lock (mutex)

Thread-safe counter

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy basics ~10 min

A counter lives in a slow external store (a database row, say) with store.read() and store.write(value).

Implement Counter(store) with increment() -> int: add 1 to the stored value and return the new value. Many threads call it at once: after n calls the store holds start + n, and no two calls return the same number.

store = ...          # holds 0
c = Counter(store)
c.increment()        # 1
c.increment()        # 2
# 8 threads each calling increment() 50 times -> store holds 402,
# and the 400 returned values are exactly 3..402

The obvious v = store.read() + 1; store.write(v) is a read-modify-write: two threads can both read 5 and both write 6. The tests' store is slow enough to make that happen.

If store.write raises, let it propagate, and later calls must still work. Don't sleep or busy-wait.

Show hint

guard the read-then-write with one threading.Lock from __init__, via with self.lock: so it's released even on an exception.

Topic: Lock (mutex). One thread in a critical section at a time.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc