An atomic, thread-safe counter
| 2 | |
| 3 | |
| 4 | class AtomicCounter: |
| 5 | """An atomic, thread-safe counter""" |
| 6 | def __init__(self, initial=0): |
| 7 | """Initialize a new atomic counter to given initial value""" |
| 8 | self._value = initial |
| 9 | self._lock = threading.Lock() |
| 10 | |
| 11 | def inc(self, num=1): |
| 12 | """Atomically increment the counter by num and return the new value""" |
| 13 | with self._lock: |
| 14 | self._value += num |
| 15 | return self._value |
| 16 | |
| 17 | def dec(self, num=1): |
| 18 | """Atomically decrement the counter by num and return the new value""" |
| 19 | with self._lock: |
| 20 | self._value -= num |
| 21 | return self._value |
| 22 | |
| 23 | @property |
| 24 | def value(self): |
| 25 | return self._value |