Free cookie consent management tool by TermsFeed The locked() method of the Lock class | Pythontic.com

The locked() method of the Lock class

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.

Acquisition and release of a lock in Python

Example:

# Example Python program that prints the 
# status of a Lock instance at various points of a 
# multithreaded program that updates a global counter

import threading

counter = 0

# Inherit from the threading.Thread class and implement
# a new thread subclass to update a counter
class CounterUpdate(threading.Thread):
    # The statements that form a thread are written inside
    # the run method. The run() method is overridden here
    def run(self):
        try:
            global counter
            self.l.acquire()
            print("Lock status before updating the counter:%s"%self.l.locked())            
            counter += 1
            print("Counter:%d"%counter)
        finally:
            self.l.release()
            print("Lock status while exiting finally block:%s"%self.l.locked())            
            print("==========")

    def __init__(self, counterLock):
        super().__init__()
        self.l = counterLock 
        print("Initial lock status:%s"%self.l.locked())

ctrLock = threading.Lock()

# Create n threads that update the counter
threads = []
threadCount = 2
for i in range(0, threadCount):
    t = CounterUpdate(ctrLock)
    threads.append(t)
    t.start()

# Wait for all the threads to complete 
# before exiting the main thread
for i in range(0, 10):
    t.join()

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

 


Copyright 2025 © pythontic.com