Last active
April 14, 2021 19:31
-
-
Save emrahgunduz/c89e9466e2bdb5e3b10be23258e58e92 to your computer and use it in GitHub Desktop.
Python thread safe counter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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