Skip to content

Instantly share code, notes, and snippets.

@Integralist
Last active January 31, 2020 11:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Integralist/339893af379763cf96bc73eb08376759 to your computer and use it in GitHub Desktop.
Save Integralist/339893af379763cf96bc73eb08376759 to your computer and use it in GitHub Desktop.
[Python Atomic Counter] #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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment