Overview:
- The locked() method returns the status of a Lock object as a Boolean value.
- A lock object can be in any of the two states:
- unlocked
- locked
- Before the code that updates a variable is reached, the Lock object has to be in locked state (through a call to the acquire() method). This makes the other threads calling the acquire() to block.
- Threads share a lock and one of them enters to update a critical resource after locking it. The other threads wait, till the update thread unlocks it (through a call to the release() method) for one of the waiting threads to lock it again.
Example:
# Example Python program that prints the import threading counter = 0 # Inherit from the threading.Thread class and implement def __init__(self, counterLock): ctrLock = threading.Lock() # Create n threads that update the counter # Wait for all the threads to complete print("Value of the counter after all the threads exit:%d"%counter) |
Output:
Initial lock status:False Lock status before updating the counter:True Initial lock status:True Counter:1 Lock status while exiting finally block:False ========== Lock status before updating the counter:True Counter:2 Lock status while exiting finally block:False ========== Value of the counter after all the threads exit:2 |