Reentrant Lock
A reentrant lock (or recursive mutex) is a mutex the owning thread can re-acquire without deadlocking itself. It tracks the owner thread and a depth counter; each lock() increments the counter, and the lock is only released when a matching number of unlock() calls bring it back to zero.
Why would you want one?
If method
A()takes a lock and calls methodB()that also takes the same lock, a plain mutex deadlocks. A reentrant lock lets the same thread pass through. Useful when public methods share a private lock and call each other.
Usually a code smell
Reaching for a reentrant lock often means the critical sections aren’t well-scoped. If you can refactor to take the lock once at the outer layer and call lock-free helpers, do that instead. Reentrant locks also hide bugs where you accidentally take a lock you already hold.
Where they show up:
- Java’s
java.util.concurrent.locks.ReentrantLock— the standard recursive mutex - POSIX:
pthread_mutexattr_settype(..., PTHREAD_MUTEX_RECURSIVE) - Rust std
Mutexis not reentrant — re-acquiring from the same thread deadlocks. Useparking_lot::ReentrantMutexif you really need it
Related
See also: Java ReentrantLock vs semaphore.