Package advene :: Package util :: Module synchronized
[hide private]
[frames] | no frames]

Source Code for Module advene.util.synchronized

 1  """ 
 2  I provi to de mechanisms similar to the ``synchronized`` keyword in Java. 
 3   
 4  The idea is to associate a reentrant lock to each object, with the possibility 
 5  for a section of code to claim that lock. Functions `enter_cs` and `exit_cs` 
 6  can be used for synchronizing any section of code on any object, while the 
 7  `synchronized` decorator can be used to synchronize a whole method on its 
 8  ``self`` parameter. 
 9  """ 
10   
11  from threading import Lock, RLock 
12   
13  # the following global lock is used to prevent several locks being created 
14  # for the same object 
15  _sync_lock = Lock() 
16   
17 -def enter_cs(obj):
18 """ 19 Enter a critical section on `obj`. 20 """ 21 _sync_lock.acquire() 22 try: 23 L = obj.__rlock 24 except AttributeError: 25 L = obj.__rlock = RLock() 26 finally: 27 _sync_lock.release() 28 L.acquire()
29
30 -def exit_cs(obj):
31 """ 32 Exit a critical section on `obj`. 33 """ 34 obj.__rlock.release()
35
36 -def synchronized(f):
37 """ 38 A decorator for synchronized methods (alla Java). 39 """ 40 def synchronized_f(self, *a, **kw): 41 enter_cs(self) 42 try: 43 return f(self, *a, **kw) 44 finally: 45 exit_cs(self)
46 synchronized_f.__name__ = f.__name__ 47 synchronized_f.__doc__ = f.__doc__ 48 return synchronized_f 49