Skip to content

Instantly share code, notes, and snippets.

@VictorZhang2014
Forked from tkhoa2711/Singleton.py
Created February 7, 2019 03:30
Show Gist options
  • Save VictorZhang2014/5df1853d213091d0c8de0db798b96aad to your computer and use it in GitHub Desktop.
Save VictorZhang2014/5df1853d213091d0c8de0db798b96aad to your computer and use it in GitHub Desktop.
A thread-safe implementation of Singleton in Python
import threading
# A thread-safe implementation of Singleton pattern
# To be used as mixin or base class
class Singleton(object):
# use special name mangling for private class-level lock
# we don't want a global lock for all the classes that use Singleton
# each class should have its own lock to reduce locking contention
__lock = threading.Lock()
# private class instance may not necessarily need name-mangling
__instance = None
@classmethod
def instance(cls):
if not cls.__instance:
with cls.__lock:
if not cls.__instance:
cls.__instance = cls()
return cls.__instance
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment