Reentrant lock¶
Category: Synchronization · Status: stub
One line: A lock that the thread already holding it may take again without deadlocking itself; it is released only when every acquisition has been undone.
Also called: recursive mutex, recursive lock, RLock.
How it connects¶
flowchart LR
n_mutex["Mutex"]
n_reentrancy["Reentrancy"]
n_reentrant_lock["Reentrant lock"]
n_reentrancy ---|vs| n_reentrant_lock
n_reentrant_lock -->|is a| n_mutex
classDef center stroke-width:3px
class n_reentrant_lock center
classDef outside stroke-dasharray: 4 3
class n_mutex,n_reentrancy outside
- Is a kind of: Mutex
- Often confused with: Reentrancy
In each language¶
| Rust | Mutex::lock ↗ is not reentrant — a second call may panic or deadlock; ReentrantLock ↗ is a nightly-only experimental API |
| Go | None: a sync.Mutex ↗ is not tied to a goroutine, so a second Lock from the same goroutine blocks like any other; RWMutex rules out recursive read-locking too |
| C | mtx_init ↗ with mtx_recursive |
| C++ | std::recursive_mutex ↗ |
| Java | Both locks are reentrant: JLS §17.1 ↗ lets a thread lock a monitor multiple times, and ReentrantLock ↗ allows up to 2147483647 recursive locks |
| Python | threading.RLock ↗ may be acquired multiple times by the same thread |
| C# | System.Threading.Lock ↗ may be entered recursively and must be exited as many times |
| Kotlin | Mutex ↗ is non-reentrant: locking it again from the coroutine that holds it suspends |
| The operating system | POSIX PTHREAD_MUTEX_RECURSIVE ↗ keeps a lock count; a Windows critical section ↗ lets its owner enter again without blocking |
Where to read more¶
- In the books: Multi-Threaded Programming in C++, Mark Walmsley — ch. 8, 'Multiple Mutexes' → 'The RECURSIVE MUTEX Class'
- In the books: Java Concurrency in Practice, Brian Goetz, Tim Peierls, Joshua Bloch, Joseph Bowbeer, David Holmes, Doug Lea — ch. 13, 'Explicit Locks' → 'Lock and ReentrantLock'
- In the books: The Art of Multiprocessor Programming, Maurice Herlihy, Nir Shavit — ch. 8, 'Monitors and Blocking Synchronization' → 'Our Own Reentrant Lock'
- Reference: Wikipedia: Reentrant mutex ↗