-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpynchronized.py
43 lines (33 loc) · 1.22 KB
/
pynchronized.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
import inspect
import threading
import multiprocessing
import functools
import time
def synchronized(obj, multiprocess=True, lock=None):
"""
Decorates a class, function or method to make it syncronized.
For a class this means only one method can be executed at a time, for a
function this means the function can be only executed once at a time.
"""
if lock == None:
lock = multiprocessing.RLock() if multiprocess else threading.RLock()
if inspect.isfunction(obj):
obj.__lock__ = lock
def sync_func(*args, **kwargs):
with lock:
return obj(*args, **kwargs)
return sync_func
elif inspect.isclass(obj):
if not hasattr(obj, '__init__'):
orig_init = lambda self: ()
else:
orig_init = obj.__init__
def __init__(self, *args, **kwargs):
self.__lock__ = lock
orig_init(self, *args, **kwargs)
obj.__init__ = __init__
for key, val in obj.__dict__.items():
if inspect.isfunction(val):
setattr(obj, key, synchronized(val, multiprocess, lock))
return obj
thread_synchronized = functools.partial(synchronized, multiprocess=False)