PracticeDev/study_python/singleton/Singleton_with_class.py

37 lines
822 B
Python
Executable File

import threading
import time
class Singleton(object):
_instance_lock = threading.Lock()
def __init__(self):
time.sleep(1)
@classmethod
def instance(cls, *args, **kwargs):
if not hasattr(Singleton, "_instance"):
with Singleton._instance_lock:
if not hasattr(Singleton, "_instance"):
print ("Init Singleton")
Singleton._instance = Singleton(*args, **kwargs)
return Singleton._instance
class MySingleton(Singleton):
def __init__(self):
import time
time.sleep(1)
print ("MySingleton")
def task(arg):
obj = Singleton.instance()
print(obj)
for i in range(20):
t = threading.Thread(target=task, args=[i,])
t.start()
time.sleep(20)
obj = Singleton.instance()
print(obj)