Python实现线程安全的单例模式
单例模式是一种常见的设计模式,该模式的主要目的是确保某一个类只有一个实例存在。当你希望在整个系统中,某个类只能出现一个实例时,单例对象就能派上用场。
比如,服务器的配置信息写在一个文件中online.conf中,客户端通过一个Config的类来读取配置文件的内容。如果在程序运行期间,有很多地方都需要使用配置文件的内容,那么每个调用配置文件的地方都会创建Config的实例,这就导致系统中存在多个Config的实例对象,在配置文件内容很多的情况下,我们就浪费了大量的内存做了同样的事。事实上,对于Config类我们在程序运行期间时只需要一个实例对象即可,这时单例模式就是最好的选择。
python的模块就是天然的单例模式,这里我们使用修饰器来实现单例模式,以下是代码实现
defSingleton(cls):
instances={}
defget_instance(*args,**kw):
ifclsnotininstances:
instances[cls]=cls(*args,**kw)
returninstances[cls]
returnget_instance
代码也很简单,将类传入单例修饰器中,如果该类还未生成实例(instances中不存在该类),那么就生成一个新的实例返回,并记录在instances中。如果已经instances中已经存在该类,那么直接返回实例instances[cls]。
那么这段代码是完美的吗?答案是否定的,这段代码不是线程安全的。要实现线程安全需要配合锁的使用,只有占有锁的线程才能继续访问单例实例,看来我们需要再写一个修饰器来实现线程安全了,以下是完整的代码实现和简单的多线程测试用例。
#!/usr/bin/python
#-*-coding:utf-8-*-
importthreading
defsynchronized(func):
func.__lock__=threading.Lock()
defsynced_func(*args,**kws):
withfunc.__lock__:
returnfunc(*args,**kws)
returnsynced_func
defSingleton(cls):
instances={}
@synchronized
defget_instance(*args,**kw):
ifclsnotininstances:
instances[cls]=cls(*args,**kw)
returninstances[cls]
returnget_instance
defworker():
single_test=test()
print"id---->%s"%id(single_test)
@Singleton
classtest():
a=1
if__name__=="__main__":
task_list=[]
foroneinrange(30):
t=threading.Thread(target=worker)
task_list.append(t)
foroneintask_list:
one.start()
foroneintask_list:
one.join()
以上内容为大家介绍了Python实现线程安全的单例模式,希望对大家有所帮助,如果想要了解更多Python相关知识,请关注IT培训机构:千锋教育。http://www.mobiletrain.org/

相关推荐HOT
更多>>
python正则表达式中的零宽断言
python正则表达式中的零宽断言1、概念有些元字符不匹配任何字符,只是简单的表示成功或失败,所以这些字符也叫零宽断言。2、符号举例(1)|或操作...详情>>
2023-11-14 11:35:03
python方法的绑定和未绑定
python方法的绑定和未绑定1、说明未绑定对象的方法:无self参数的方法,通过定义类调用函数,返回未绑定self的方法。绑定对象的方法:带self参...详情>>
2023-11-14 09:53:02
python海象运算符的使用
python海象运算符的使用1、在判断条件下允许操作。在一定程度上简化了代码,但降低了可读性。i=len((l:=[1,2,3]))#先对l进行赋值,在对i赋值whi...详情>>
2023-11-14 02:38:21
pythonelif语句报错是什么原因
python的else和elif语句也可以叫做子句,因为它们不能独立使用,两者都是出现在if、for、while语句内部的。else子句可以增加一种选择;而elif子...详情>>
2023-11-13 21:46:35热门推荐
技术干货






