import threading class AtomicCounter: def __init__(self, initial=0): self.value = initial self._lock = threading.Lock() def increment(self, num=1): with self._lock: self.value += num return self.value
Some late nitpicking, sorry:
This is not an atomic counter, it's a thread-safe counter. And since being thread-safe is rarely a bad idea, especially assuming someone will manage to Kill GIL, I would just call it a "counter" or Counter.
(Of course, atomic/lock-free implementations are nice when possible.)