Categories: python

RLock Object in Python

RLock (re-entrant lock) is a type of lock that allows the holder of the lock to acquire it multiple times without causing a deadlock. This can be useful in situations where a thread needs to acquire the same lock multiple times while performing some operation.

Note: If a code can be safely called again, it is re-entrant. In other words, re-entrant code can be called multiple times and still function correctly even if called by different threads. As a result, the re-entrant section of code typically uses local variables only in such a way that each call to the code receives its own unique copy of data.

Re-entrant code:

def f(i): return i + 2 
def h(i): return f(i) + 2;

Normal Lock objects can only be obtained once, even by the same thread. If a lock is accessed by more than one function in the same call chain, this can have unintended consequences:

Example:

import threading

lock = threading.Lock()

print 'First try :', lock.acquire()
print 'Second try:', lock.acquire()

print "print this if not blocked..."

Output:

First try : True
Second try:

So, as in the example above, in a situation where separate code from the same thread needs to “re-acquire” the lock, we need to use threading.RLock instead of simple threading.Lock():

import threading

lock = threading.RLock()

print 'First try :', lock.acquire()
print 'Second try:', lock.acquire(0)

Output:

First try : True
Second try: 1

The output shows that we’re able to “re-acquire” the lock.

Note: also read about Lock Object in Python

Follow Me

Please follow me to read my latest post on programming and technology if you like my post.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Recent Posts

Generate Parenthesis | Intuition + Code | Recursion Tree | Backtracking | Java

Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…

3 months ago

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

2 years ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

2 years ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

2 years ago