11. Synchronization with locks
In the previous lectures we have been talking about locks. We can use either the standard threading.Lock or threading.RLock class that is the re-entrant lock
the standard Lock can be acquired once before it must be released - on the other hand, RLocks can be acquired multiple times from the same thread (no matter that it has been already acquired)
RLock must be released the same number of times it has been acquired
with Locks: the acquired lock can be released any thread
RLocks can be released by the thread that acquired it exclusively
Ok so a thread cannot acquire a lock owned by another thread. But a given thread can acquire a lock that it already owns. Allowing a thread to acquire the same lock more than once is called re-entrant synchronization. And this is exactly what is happening in Python with RLocks - the same thread may acquire the lock more than once.
For example: let's consider recursive method calls. If a given thread calls a recursive and synchronized method several times then it is fine (note that in this case the same thread "enters" the synchronized block several times). There will be no deadlock because of re-entrant synchronization.
نظرات