-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsingleton.py
More file actions
40 lines (31 loc) · 905 Bytes
/
Copy pathsingleton.py
File metadata and controls
40 lines (31 loc) · 905 Bytes
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
import threading
import time
mutex = threading.Lock()
def singleton(_class):
_instance = {}
def wrap(*args, **kwargs):
with mutex:
if _class not in _instance:
_instance[_class] = _class(*args, **kwargs)
return _instance[_class]
return wrap
#
# Example usage
#
@singleton
class Test(object):
def _init_(self, name):
self.name = name
def run(now, i, name):
print('thread {i} {name} running'.format(i=i, name=name))
while int(time.time() - 1) < now:
time.sleep(0.00001)
t = Test(name)
print(i, name, t.name)
if __name__ == '__main__':
names = ['aap', 'noot', 'mies', 'teun', 'vuur', 'gijs', 'wim', 'weide', 'does', 'kip']
threads = {}
now = int(time.time())
for i in range(0, 10):
threads[i] = threading.Thread(target=run, args=(now, i, names[i],))
threads[i].start()