Singleton Pattern 是针对class的一种软件设计模式,用以确保该class在系统的生命周期内仅存在唯一一个实例。此文仅用于记录本人所常选用的一种单例模式,更多单例模式的实现方法参考一下连接:
werediver/singleton.py
Python单例模式
Python中的单例模式的几种实现方式的及优化
设计模式(Python)-单例模式
import time
import threading
class Singleton(object):
_instance = None
_instance_lock = threading.Lock()
def __init__(self):
pass
@classmethod
def instance(cls):
with cls._instance_lock:
if not cls._instance:
cls._instance = cls()
return cls._instance
def task(arg):
obj = Singleton.instance()
print(obj)
for i in range(10):
t = threading.Thread(target=task,args=[i,])
t.start()
time.sleep(20)
obj = Singleton.instance()
print(obj)
其中
with some_lock:
# do something...
等同于
some_lock.acquire()
try:
# do something...
finally:
some_lock.release()
网友评论