Skip to content

Instantly share code, notes, and snippets.

@emrahgunduz
Last active April 14, 2021 19:31
Show Gist options
  • Save emrahgunduz/c89e9466e2bdb5e3b10be23258e58e92 to your computer and use it in GitHub Desktop.
Save emrahgunduz/c89e9466e2bdb5e3b10be23258e58e92 to your computer and use it in GitHub Desktop.
Python thread safe counter
from threading import Lock
class Counter( object ):
def __init__ ( self ):
self.__value = 0
self.__lock = Lock()
def increment ( self, by_value: int = 1 ):
with self.__lock:
self.__value += by_value
def decrement ( self, by_value: int = 1, no_minus: bool = True ):
with self.__lock:
self.__value -= by_value
if no_minus and self.__value < 0:
self.__value = 0
def set ( self, value: int ):
with self.__lock:
self.__value = value
def get ( self ) -> int:
with self.__lock:
return self.__value
@property
def value ( self ) -> int:
with self.__lock:
return self.__value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment