使用python写一个线程安全的单例模式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | # 使用python写一个线程安全的单例模式 # 参考:https://juejin.cn/post/6844903951624585229 import threading import time def synchronized(func): func.__lock__ = threading.Lock() def lock_func( * args, * * kwargs): with func.__lock__: return func( * args, * * kwargs) return lock_func class Singleton( object ): instance = None @synchronized def __new__( cls , * args, * * kwargs): # type kwargs: object if cls .instance is None : time.sleep( 0.5 ) cls .instance = super ().__new__( cls ) return cls .instance class MyClass(Singleton): def __init__( self , a): self .a = a def check(lst): for i in range ( len (lst)): if i > 0 and id (lst[i]) ! = id (lst[i - 1 ]): return False return True def test(n): def func(): obj = Singleton( 9 ) print ( id (obj)) for i in range (n): thread = threading.Thread(target = func) thread.start() if __name__ = = "__main__" : test( 10 ) # 31744710112483174471011248 # # 31744710112483174471011248 # 3174471011248 # # 3174471011248 # 3174471011248 # 3174471011248 # 3174471011248 # 3174471011248 |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
2019-08-10 Radmin自动登录器 v3.0