-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsingleton.py
40 lines (29 loc) · 955 Bytes
/
singleton.py
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
#不推荐会重复执行init 会重新加载一次init的数据
import threading
class Singleton:
_instance_lock = threading.Lock()
def __new__(cls, *args, **kwargs):
if not hasattr(Singleton, "_instance"):
with Singleton._instance_lock:
if not hasattr(Singleton, "_instance"): Singleton._instance = super().__new__(cls)
return Singleton._instance
def __init__(self):
pass
#推荐
import threading
def Singleton(cls):
_instance = {}
lock = threading.RLock()#lock = threading.Lock() 如果单例里面调用单例可能死锁
def _singleton(*args, **kargs):
if cls not in _instance:
with lock:
if cls not in _instance:
_instance[cls] = cls(*args, **kargs)
return _instance[cls]
return _singletons
@Singleton
class Demo():
def __init__(self):
pass
func = Singleton(Demo)
func()