Created
September 8, 2019 14:15
-
-
Save daimon99/b632437d0566a6bcdcc0ffbf4bb55128 to your computer and use it in GitHub Desktop.
python singleton
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
class Singleton(type): | |
_instances = {} | |
def __call__(cls, *args, **kwargs): | |
if cls not in cls._instances: | |
cls._instances[cls] = super().__call__(*args, **kwargs) | |
return cls._instances[cls] |
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
import torch | |
import logging | |
import threading | |
from singleton import Singleton | |
log = logging.getLogger(__name__) | |
lock = threading.RLock() | |
class XxxService(metaclass=Singleton): | |
def __init__(self): | |
pass | |
def xxx(self): | |
with lock: | |
pass | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment