Free cookie consent management tool by TermsFeed The release() method of RLock class in Python | Pythontic.com

The release() method of RLock class in Python

Overview:

  • The release() method of the RLock class transitions an RLock object from locked state to unlocked state.
  • Prior to calling release() if a thread has called acquire() “n” number of times, then release() must be called equal number of times to unlock the RLock object.
  • After a call to acquire() method an Rlock object is in locked state and the thread called the acquire() method owns the lock. Only a thread that owns the RLock object can call the release() method. After release() the lock is not owned by any thread until the next acquire() method succeeds from one of the waiting threads.
  • When the RLock object is in unlocked state calling release() will make Python to raise an Exception stating RuntimeError: cannot release un-acquired lock.

Example:

# Example Python program that uses the
# same RLock object inside multiple methods
# of a class
import threading as th

# Trivial definition of a shopping cart
class Cart:
    def __init__(self, cartLock):
        self.items     = []
        self.lock     = cartLock

    def addItem(self, item):
        with self.lock:
            print(self.lock)
            self.items.append(item)
        print(self.lock)    

    def removeItem(self, item):
        with self.lock:
            self.items.remove(item)        

    def addRemoveItem(self, toAdd, toRemove):
        with self.lock:
            print(self.lock)
            self.addItem(toAdd)
            self.removeItem(toRemove)
        print(self.lock)


    def printItems(self):
        with self.lock:
            for item in self.items:
                print(item)

# Create a reentrant lock
lock = th.RLock()
cart = Cart(lock)

# Add/remove items
cart.addItem("Sugar")
cart.addItem("Juice")
cart.addRemoveItem("Protein", "Sugar")

# Print the items
cart.printItems()

Output:

<locked _thread.RLock object owner=8030314176 count=1 at 0x43f1c387b40>
<unlocked _thread.RLock object owner=0 count=0 at 0x43f1c387b40>
<locked _thread.RLock object owner=8030314176 count=1 at 0x43f1c387b40>
<unlocked _thread.RLock object owner=0 count=0 at 0x43f1c387b40>
<locked _thread.RLock object owner=8030314176 count=1 at 0x43f1c387b40>
<locked _thread.RLock object owner=8030314176 count=2 at 0x43f1c387b40>
<locked _thread.RLock object owner=8030314176 count=1 at 0x43f1c387b40>
<unlocked _thread.RLock object owner=0 count=0 at 0x43f1c387b40>
Juice
Protein

 


Copyright 2025 © pythontic.com