-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtestsingle.py
More file actions
48 lines (37 loc) · 1.18 KB
/
testsingle.py
File metadata and controls
48 lines (37 loc) · 1.18 KB
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
import threading
import time
class Singleton(object):
_instance_lock = threading.Lock()
def __init__(self, cls):
self._cls = cls
self._instance = {}
# def __call__(self, *args, **kwargs):
# if self._cls not in self._instance:
# time.sleep(1)
# self._instance_lock.acquire()
# try:
# if self._cls not in self._instance:
# self._instance[self._cls] = self._cls(*args, **kwargs)
# finally:
# self._instance_lock.release()
# return self._instance[self._cls]
def __call__(self, *args, **kwargs):
if self._cls not in self._instance:
time.sleep(1)
with self._instance_lock:
time.sleep(1)
if self._cls not in self._instance:
time.sleep(1)
self._instance[self._cls] = self._cls(*args, **kwargs)
return self._instance[self._cls]
@Singleton
class A(object):
a = 1
def __init__(self, x=0):
self.x = x
def task(arg):
obj = A(arg)
print(id(obj))
for i in range(10):
t = threading.Thread(target=task,args=[i,])
t.start()