Skip to content

Instantly share code, notes, and snippets.

@emrahgunduz
Last active April 14, 2021 19:31
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
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