Python实现多线程安全单例模式
在开发过程中,时常需要某些对象在软件整个运行生命周期只需存在一个副本,比如服务器加载的参数配置等等,有种现成的设计模式专干这种活---单例模式,能很好的适用这种需求场景。而由于Python动态语言的灵活性,相对于其它编程语言的实现尤为优雅、简洁、方便,实现代码如下:
class Application(object):
def __init__(self):
self.args = "Hello world"
@classmethod
def instance(cls):
if not hasattr(cls, "_instance"):
cls._instance = cls()
return cls._instance
以下是多线程测试代码:def __init__(self):
self.args = "Hello world"
@classmethod
def instance(cls):
if not hasattr(cls, "_instance"):
cls._instance = cls()
return cls._instance
class Work(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.start()
def run(self):
app = Application.instance()
print threading.current_thread(), id(app)
time.sleep(.1)
if __name__ == "__main__":
for i in range(10):
Work()
测试结果如下:def __init__(self):
threading.Thread.__init__(self)
self.start()
def run(self):
app = Application.instance()
print threading.current_thread(), id(app)
time.sleep(.1)
if __name__ == "__main__":
for i in range(10):
Work()
<Work(Thread-1, started -1218360464)> 3076741900
<Work(Thread-2, started -1226753168)> 3076741900
<Work(Thread-3, started -1235145872)> 3076741900
<Work(Thread-4, started -1243538576)> 3076741900
<Work(Thread-5, started -1251931280)> 3076741900
<Work(Thread-6, started -1260323984)> 3076741900
<Work(Thread-7, started -1268716688)> 3076741900
<Work(Thread-8, started -1277109392)> 3076741900
<Work(Thread-9, started -1285502096)> 3076741900
<Work(Thread-10, started -1293894800)> 3076741900
<Work(Thread-2, started -1226753168)> 3076741900
<Work(Thread-3, started -1235145872)> 3076741900
<Work(Thread-4, started -1243538576)> 3076741900
<Work(Thread-5, started -1251931280)> 3076741900
<Work(Thread-6, started -1260323984)> 3076741900
<Work(Thread-7, started -1268716688)> 3076741900
<Work(Thread-8, started -1277109392)> 3076741900
<Work(Thread-9, started -1285502096)> 3076741900
<Work(Thread-10, started -1293894800)> 3076741900
推荐(
反对(