Skip to main content

Practice ยท 1 of 1

A counter that survives concurrency

Implement SafeCounter with inc() and a read-only .value property that stays EXACT under concurrent increments. The graded test starts 6 threads, each calling inc() 20 times, twice. Under that concurrency any lock-free read-modify-write (value = self.value; ...; self.value = value + 1) โ€” especially one that does any work between read and write โ€” loses updates. Guard the state with a threading.Lock.

Difficulty: advanced

Back to lesson: Practice: Thread Safety Practice