Tags: #python3 #concurrency #threadsafe #lock #atomic #counter
import threading
class AtomicCounter(object):
"""An atomic, thread-safe counter"""
def __init__(self, initial=0):
"""Initialize a new atomic counter to given initial value"""
self._value = initial
self._lock = threading.Lock()
def inc(self, num=1):
"""Atomically increment the counter by num and return the new value"""
with self._lock:
self._value += num
return self._value
def dec(self, num=1):
"""Atomically decrement the counter by num and return the new value"""
with self._lock:
self._value -= num
return self._value
@property
def value(self):
return self._value
counter = AtomicCounter()
counter.value # 0
counter.inc() # 1
counter.inc() # 2
counter.dec() # 1
counter.dec() # 0
counter.dec() # -1