Skip to content

Instantly share code, notes, and snippets.

@emrahgunduz
Last active Apr 14, 2021
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