Lock Objects

A primitive lock (or mutual exclusion lock) is a synchronization primitive that's in either a "locked" or "unlocked" state. Two methods, acquire() and release(), are used to change the state of the lock. If the state is locked, attempts to acquire the lock are blocked until the lock is released. If more than one thread is waiting to acquire the lock, only one is allowed to proceed when the lock is released. The order in which waiting threads proceed is undefined.

A new Lock instance is created using the following constructor:

Creates a new Lock object that's initially unlocked.

A Lock instance, lock, supports the following methods:

lock.acquire([blocking ])

Acquires the lock, blocking until the lock is released if necessary. If blocking is supplied and set to False, the function returns immediately with a value of False if the lock could not be acquired or True if locking was successful.


Releases a lock. It's an error to call this method when the lock is in an unlocked state or from a different thread than the one that originally called acquire().


A reentrant lock is a synchronization primitive that's similar to a Lock object, but it can be acquired multiple times by the same thread. This allows the thread owning the lock to perform nested acquire() and release() operations. In this case, only the outermost release() operation resets the lock to its unlocked state. A new RLock object is created using the following constructor:


Creates a new reentrant lock object. An RLock object, rlock, supports the following methods:

rlock.acquire([blocking ])

Acquires the lock, blocking until the lock is released if necessary. If no thread owns the lock, it's locked and the recursion level is set to l. If this thread already owns the lock, the recursion level of the lock is increased by one and the function returns immediately.


Releases a lock by decrementing its recursion level. If the recursion level is zero after the decrement, the lock is reset to the unlocked state. Otherwise, the lock remains locked. This function should only be called by the thread that currently owns the lock.

0 0

Post a comment