Python RLock acquire() Method with Example

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

Python RLock.acquire() Method

The RLock.acquire() is an inbuilt method of the RLock class of the threading module. The RLock class objects follow reentrancy. A reentrant lock must be released by the thread that acquired it. Once a thread has acquired a reentrant lock, the same thread may acquire it again without blocking; and the thread must release it once for each time it has acquired it. The acquire() method is used to acquire a lock, either blocking or non-blocking.

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 RLock

Syntax

The following is the syntax of acquire() method:

acquire( blocking=True, timeout=-1)

Parameter(s)

The following are the parameter(s):

  • blocking: It is an optional parameter, which works as a blocking flag. Its default value is True. If,
    • The value is True: If the thread already owns the lock, increment the recursion level by one and return; and if another thread owns the lock, block until the lock is released by that thread. Once the thread gets released, acquire the lock and increment the recursion level by one and return.
    • The value is False: Don't block.
  • timeout: It is an optional parameter, which specifies the number of seconds for which the calling thread will be blocked if some other method is acquiring the lock currently. Its default value is -1 which indicates that the thread will be blocked for an indefinite time till it acquires the lock.

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 if lock was successfully acquired else returns False.

Example of RLock.acquire() Method in Python

# program to illustrate the use of 
# acquire() method in RLock class
  
# importing the module 
import threading 
  
# initializing the shared resource 
x = 0
  
# creating an RLock object  
rlock = threading.RLock() 
  
# Creating first thread
rlock.acquire() 
x = x + 1
  
# the below thread is trying to access  
# the shared resource  
rlock.acquire()  
x = x + 2
rlock.release()

rlock.release() 
# Rlock released by both the threads
  
# displaying the value of shared resource 
print("Displaying the final value of the shared resource x:", x)

Output

Displaying the final value of the shared resource x: 3



Comments and Discussions!

Load comments ↻





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