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相关知识,请关注多测师。https://www.e70w.com/xwzx/

猜你喜欢LIKE
相关推荐HOT
更多>>
如何使用python中的add函数?
如何使用python中的add函数?本文教程操作环境:windows7系统、Python3.9.1,DELLG3电脑。add函数使用方法1、numpy中加法运算使用实例importnump...详情>>
2023-11-14 14:11:16
python如何将九九乘法表写入到Excel?
python如何将九九乘法表写入到Excel?现在使用python去输出九九乘法表,已经不再稀奇,我们经常输出的环境是文本,但是今天教大家更为复杂一点的...详情>>
2023-11-14 12:11:28
python中altair可视化库怎么用?
python中altair可视化库怎么用?作为六大python可视化库,基本上学会都是可以通吃任何领域的存在,本章要给大家介绍的Altair就是其中之一的可视...详情>>
2023-11-14 09:40:29
python中最小二乘法如何理解?
python中最小二乘法如何理解?python中在实现一元线性回归时会使用最小二乘法,那你知道最小二乘法是什么吗。其实最小二乘法为分类回归算法的基...详情>>
2023-11-14 06:58:12热门推荐
如何使用python中的add函数?
沸python中dir函数如何使用?
热python中merge函数如何使用?
热python中str内置函数总结归纳
新python如何将九九乘法表写入到Excel?
Python的scikit-image模块是什么?
python timedelta函数是什么?
python中如何使用np.concatenate()拼接numpy数组
Python jieba库分词模式怎么用?
python中altair可视化库怎么用?
TCP在python中如何连接服务器?
python中使用__slots__定义类属性
python中的unittest框架是什么?
python字典获取对应键的方法
技术干货






