Python Condition acquire() Method with Example

Python Condition.acquire() Method: In this tutorial, we will learn about the acquire() method of Condition class in Python with its usage, syntax, and examples. By Hritika Rajput Last updated : April 25, 2023

Python Condition.acquire() Method

The Condition.acquire() is an inbuilt method of the Condition class of the threading module. The Condition class implements condition variable objects. A condition variable allows one or more threads to wait until they are notified by another thread. Acquire method is used to acquire a lock. It calls the corresponding method on the underlying lock and returns the method value.

The Producer-Consumer problem works as a perfect use case for Condition object in multithreading. In this problem, there is one producer that produces some item and one consumer consuming the item. Until the Producer has not produced an item, the Consumer cannot consume it. Therefore, it waits for the Producer to produce an item. Also, it is the duty of the Producer to inform the Consumer that an item has been produced and is now available for consumption. If there are multiple consumers, then the Producer must inform all the Consumers about the new item.

Module

The following module is required to use acquire() method:

import threading

Class

The following class is required to use acquire() method:

from threading import Condition 

Syntax

The following is the syntax of acquire() method:

acquire(*args)

Parameter(s)

The following are the parameter(s):

  • args: It is an optional parameter, specifying the arguments we can put in the acquire() method.

Return Value

The return type of this method is <class 'bool'>. The method is used to acquire a lock while implementing multithreading and returns True is lock was successfully acquired else returns False.

Example of Condition.acquire() Method in Python

# use of acquire() method for Condition object

import threading
import time
import random

class subclass:
  # Initialising the shared resources
  def __init__(self):
    self.x = []
  
  # Add an item for the producer
  def produce_item(self, x_item):
    print("Producer adding an item to the list")
    self.x.append(x_item)
    
  # Consume an item for the consumer
  def consume_item(self):
    print("Consuming from the list")
    consumed_item = self.x[0]
    print("Consumed item: ", consumed_item)
    self.x.remove(consumed_item)

def producer(subclass_obj, condition_obj):
    # Selecting a random number from the 1 to 3
    r = random.randint(1,3)
    print("Random number selected was:", r)
    
    # Creting r number of items by the producer
    for i in range(1, r):
      print("Producing an item, time it will take(seconds): " + str(i))
      time.sleep(i)
      
      print("Producer acquiring the lock")
      condition_obj.acquire()
      try:
        # Produce an item
        subclass_obj.produce_item(i)
        # Notify that an item  has been produced
        condition_obj.notify()
      finally:
        # Releasing the lock after producing
        condition_obj.release()
      
def consumer(subclass_obj, condition_obj):
    condition_obj.acquire()
    while True:
      try:
        # Consume the item 
        subclass_obj.consume_item()
      except:
        print("No item to consume, list empty")
        print("Waiting for 10 seconds")
        # wait with a maximum timeout of 10 sec
        value = condition_obj.wait(10)
        if value:
          print("Item produced notified")
          continue
        else:
          print("Waiting timeout")
          break
        
    # Releasig the lock after consuming
    condition_obj.release()
    
if __name__=='__main__':
    
  # Initialising a condition class object
  condition_obj = threading.Condition()
  # subclass object
  subclass_obj = subclass()
  
  # Producer thread
  pro = threading.Thread(target=producer, args=(subclass_obj,condition_obj,))
  pro.start()
  
  # consumer thread
  con = threading.Thread(target=consumer, args=(subclass_obj,condition_obj,))
  con.start()

  pro.join()
  con.join()
  print("Producer Consumer code executed")

Output

Random number selected was: 3
Producing an item, time it will take(seconds): 1
Consuming from the list
No item to consume, list empty
Waiting for 10 seconds
Producer acquiring the lock
Producer adding an item to the list
Item produced notified
Consuming from the list
Consumed item:  1
Consuming from the list
No item to consume, list empty
Waiting for 10 seconds
Producing an item, time it will take(seconds): 2
Producer acquiring the lock
Producer adding an item to the list
Item produced notified
Consuming from the list
Consumed item:  2
Consuming from the list
No item to consume, list empty
Waiting for 10 seconds
Waiting timeout
Producer Consumer code executed



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.