24 classes used to protect method from simultaneous access by different
25 threads. The primary class is LockProtected.
27 from builtins
import object
30 SharedLock = threading.RLock
35 a class that assists in keeping methods thread-safe.
37 This class is intended to be enlisted as a base class to the class being
38 protected. A method that is to be protected from simultaneous access
39 would include (at its beginning) a call to _checkLocked():
41 class MyClass(BaseClass, LockProtected):
42 def __init__(self, lock=SharedLock):
43 LockProtected.__init__(self, lock)
50 Doing so will require that the protected class be "locked" before a
51 protected method can be called or else an UnsafeAccessError will be
52 raised. Locking is done via the with statement:
58 For the locking to work, the protected class must provide to the
59 LockProtected constructor a lock object. Typically this is a
60 lsst.utils.multithreading.SharedLock instance or, if one wants to
61 employ thread notification techniques, a
62 lsst.utils.multithreading.SharedData instance. It should at least
63 be a reentrant lock--that is, having the behavior of threading.RLock
64 (from the standard Python Library).
66 This class is primarily intended for protecting methods across multiple
67 classes together via a single lock. That is, it can prevent simultaneous
68 access to any protected method across multiple class instances. To
69 accomplish this, each class to be protected should accept a lock as
70 a constructor argument. Then the same lock is passed into all of the
71 constructors that need protection together.
76 initialize the lock protection
77 @param lock a reentrant lock instance to use. If None, the
78 protection behavior is disabled.
85 self._lp_lock.acquire()
87 def __exit__(self, exc_type, exc_value, traceback):
89 self._lp_lock.release()
92 def _checkLocked(self):
93 if self.
_lp_lock and not self._lp_lock._is_owned():
99 an exception that is raised when one attempts to access a protected
100 method without first acquiring the lock on its class.
105 msg =
"Programmer Error: failed to obtain lock via with statement"
106 Exception.__init__(self, msg)