-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsynchronized.py
executable file
·64 lines (43 loc) · 1.62 KB
/
synchronized.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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import _thread
import threading
import types
def synchronized_with_attr(lock_name):
def decorator(method):
def synced_method(self, *args, **kws):
lock = getattr(self, lock_name)
with lock:
return method(self, *args, **kws)
return synced_method
return decorator
def syncronized_with(lock):
def synchronized_obj(obj):
if type(obj) is types.FunctionType:
obj.__lock__ = lock
def func(*args, **kws):
with lock:
obj(*args, **kws)
return func
elif isinstance(obj, type):
orig_init = obj.__init__
def __init__(self, *args, **kws):
self.__lock__ = lock
orig_init(self, *args, **kws)
obj.__init__ = __init__
for key in obj.__dict__:
val = obj.__dict__[key]
if type(val) is types.FunctionType:
decorator = syncronized_with(lock)
obj.__dict__[key] = decorator(val)
return obj
return synchronized_obj
def synchronized(item):
if type(item) is str:
decorator = synchronized_with_attr(item)
return decorator(item)
if type(item) is _thread.LockType:
decorator = syncronized_with(item)
return decorator(item)
else:
new_lock = threading.Lock()
decorator = syncronized_with(new_lock)
return decorator(item)