Python RLock: Reentrant Locking Explained
Learn how Python's RLock lets the same thread acquire a lock multiple times, preventing deadlocks in recursive and nested code. Includes examples and tradeoffs.

Python's threading.RLock is a reentrant lock: a thread that already holds the lock can acquire it again without blocking. This makes it useful when nested code paths need to share the same lock. This guide explains how RLock behaves, when to use it, and how it compares with a standard Lock.
A standard threading.Lock is not reentrant. If the same thread tries to acquire it again before releasing it, the thread blocks forever. This becomes a problem when a function that holds a lock calls another function that also needs that same lock. Python's threading.RLock (reentrant lock) solves this by allowing the thread that already holds the lock to acquire it again without deadlocking.
The Problem with a Standard Lock in Nested Calls
Consider a simple counter class that uses a Lock to protect its internal state. If one public method calls another public method and both try to acquire the same lock, the second acquisition will block because the first lock hasn't been released yet.
import threading
class Counter:
def __init__(self):
self._value = 0
self._lock = threading.Lock()
def increment(self):
with self._lock:
self._value += 1
self._increment_by_two()
def _increment_by_two(self):
with self._lock:
self._value += 2Calling increment() will deadlock because _increment_by_two() tries to acquire the same Lock while the calling thread already holds it. The standard Lock is not reentrant, so the thread cannot reacquire it.
What RLock Does Differently
An RLock (reentrant lock) tracks the owning thread and a recursion count. When a thread acquires an RLock, it increments the count. If the same thread attempts to acquire it again, the count is incremented again instead of blocking. Each release decrements the count. The lock is only truly released when the count reaches zero, and only the owning thread can release it.
This behavior makes RLock suitable for scenarios where a thread may need to enter the same critical section multiple times, either through direct recursion or through nested calls that share a lock.
When Reentrant Locking Is the Right Choice
Use an RLock when you have a clear need for reentrancy:
- Recursive functions that acquire a lock at each recursion level.
- Public methods that call other methods on the same object, all of which need the same lock.
- Callback or event-driven code where the same thread may re-enter a lock-protected section through a different code path.
If your code does not require reentrancy, a standard Lock is simpler and slightly faster. Reaching for RLock just because it exists adds unnecessary complexity and can hide design problems.
Practical Example: Recursive Function with RLock
Here is the same counter example rewritten with an RLock:
import threading
class Counter:
def __init__(self):
self._value = 0
self._lock = threading.RLock()
def increment(self):
with self._lock:
self._value += 1
self._increment_by_two()
def _increment_by_two(self):
with self._lock:
self._value += 2Now increment() works without deadlocking. The same thread acquires the RLock twice, and the recursion count goes from 1 to 2. When _increment_by_two() exits its with block, the count drops back to 1. When increment() exits, it drops to 0 and the lock is released.
You can also use RLock in a recursive function directly:
import threading
lock = threading.RLock()
def recursive_count(n):
with lock:
if n <= 0:
return
recursive_count(n - 1)Each recursive call acquires the lock again, and the recursion depth is tracked by the lock's internal counter.
Common Mistakes and Edge Cases
An RLock is not a free pass to ignore locking discipline. Several pitfalls remain:
- Releasing more times than acquiring raises
RuntimeError. Always pair eachacquirewith arelease, preferably usingwithstatements. - A different thread cannot release the lock. If thread A acquires an
RLock, thread B callingrelease()will raiseRuntimeError. The lock is owned by thread A until the recursion count reaches zero. RLockdoes not protect against race conditions. It only prevents deadlock from reentrancy. If your code has a race condition, anRLockwill not fix it.- Using
RLockin awithstatement is safe, but manually callingacquireandreleaserequires careful exception handling to ensure the lock is released even if an error occurs.
Performance and Overhead Considerations
An RLock carries slightly more overhead than a standard Lock because it must track the owning thread and the recursion count. In practice, this difference is negligible for most applications. The real cost comes from contention: when multiple threads compete for the same lock, the operating system must manage waiting threads. RLock does not change that.
If you are in a hot path with heavy lock contention, consider reducing the critical section size or using a more fine-grained locking strategy. The extra bookkeeping in an RLock is usually small compared with contention costs.
Choosing Between Lock and RLock
Use a standard Lock when:
- Your critical section is a single, non-recursive block.
- You want the simplest possible synchronization primitive.
- You are certain that no thread will ever attempt to reacquire the same lock.
Use an RLock when:
- You have nested or recursive code that must share the same lock.
- You are building a class where public methods call each other and all need the same lock.
- You need to ensure that a thread can safely re-enter a lock-protected region without deadlocking.
There is no universally better choice. The decision depends on the structure of your code. If you are unsure whether reentrancy is needed, start with a Lock and switch to RLock only when you encounter a deadlock caused by reentrant acquisition. This keeps your synchronization logic as explicit as possible and avoids masking design issues that might be better solved by refactoring the code to use a single lock acquisition point.
Try matching browser tools
All toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesPython iter(): How the Built-in Function Works
Explains Python's iter() built-in: how it creates iterators, the two-argument sentinel form, custom iterator classes, and common edge cases.
Python Pika: Queues, Exchanges, Routing Keys, and Acknowledgements
Learn how to use Python's Pika client with RabbitMQ: declare queues and exchanges, publish with routing keys, consume messages, and handle acknowledgements reliably.
Python Kafka: kafka-python vs Confluent Client
python kafka python vs confluent kafka: Compare kafka-python and Confluent Kafka Python clients: API differences, performance, feature coverage, and when to choose eac...
Python Kafka Offsets, Partitions, and Manual Commits
Learn how Kafka offsets and partitions work and how to manually commit offsets in Python consumers with kafka-python and confluent-kafka. Covers sync vs async commits, rebalances, and seeking.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.