← Blog

RLock vs Lock in Python: Understanding Reentrant Thread Synchronization

In multithreaded Python applications, multiple threads may need to access the same shared resource. Without coordination, concurrent updates can cause race conditions and inconsistent state. The threading module provides synchronization primitives such as Lock and RLock to protect critical sections.

I originally published this comparison on DEV Community. This post is included here as part of my technical writing archive.

threading.Lock: a basic mutual-exclusion lock

A Lock allows one thread at a time to enter a protected section. When a thread acquires it, another thread attempting to acquire the same lock must wait until it is released.

A standard Lock is not reentrant. If code attempts to acquire the same lock again while already holding it, it can block indefinitely. This can happen when a lock-protected method calls another method that tries to acquire that same lock.

threading.RLock: a reentrant lock

An RLock allows the thread that already owns the lock to acquire it again. Python tracks the owning thread and the number of acquisitions. Each successful acquire() must be matched by a corresponding release() before another thread can acquire the lock.

This behaviour is useful for recursive functions and nested method calls where multiple layers may need to protect the same shared state.

Choosing between them

  • Use Lock when the critical section is straightforward and the same thread will not need to acquire the lock recursively or through nested calls.
  • Use RLock when reentrant access is part of the design, such as a public method calling another method protected by the same lock.

An RLock has additional ownership and recursion-count bookkeeping, so it is not automatically a better or safer choice. Prefer the simpler Lock when reentrancy is unnecessary. In either case, use context managers (with lock:) to ensure the lock is released even if an exception occurs.

Understanding this distinction helps prevent deadlocks and makes concurrent Python code easier to reason about.

Read the original article: R-Lock vs Lock in Python on DEV Community