Struct std::sync::remutex::ReentrantMutex
source · pub struct ReentrantMutex<T> {
mutex: Mutex,
owner: AtomicUsize,
lock_count: UnsafeCell<u32>,
data: T,
}
Expand description
A reentrant mutual exclusion
This mutex will block other threads waiting for the lock to become available. The thread which has already locked the mutex can lock it multiple times without blocking, preventing a common source of deadlocks.
This is used by stdout().lock() and friends.
Implementation details
The ‘owner’ field tracks which thread has locked the mutex.
We use current_thread_unique_ptr() as the thread identifier, which is just the address of a thread local variable.
If owner
is set to the identifier of the current thread,
we assume the mutex is already locked and instead of locking it again,
we increment lock_count
.
When unlocking, we decrement lock_count
, and only unlock the mutex when
it reaches zero.
lock_count
is protected by the mutex and only accessed by the thread that has
locked the mutex, so needs no synchronization.
owner
can be checked by other threads that want to see if they already
hold the lock, so needs to be atomic. If it compares equal, we’re on the
same thread that holds the mutex and memory access can use relaxed ordering
since we’re not dealing with multiple threads. If it’s not equal,
synchronization is left to the mutex, making relaxed memory ordering for
the owner
field fine in all cases.
Fields§
§mutex: Mutex
§owner: AtomicUsize
§lock_count: UnsafeCell<u32>
§data: T
Implementations§
source§impl<T> ReentrantMutex<T>
impl<T> ReentrantMutex<T>
sourcepub const fn new(t: T) -> ReentrantMutex<T>
pub const fn new(t: T) -> ReentrantMutex<T>
Creates a new reentrant mutex in an unlocked state.
sourcepub fn lock(&self) -> ReentrantMutexGuard<'_, T>
pub fn lock(&self) -> ReentrantMutexGuard<'_, T>
Acquires a mutex, blocking the current thread until it is able to do so.
This function will block the caller until it is available to acquire the mutex. Upon returning, the thread is the only thread with the mutex held. When the thread calling this method already holds the lock, the call shall succeed without blocking.
Errors
If another user of this mutex panicked while holding the mutex, then this call will return failure if the mutex would otherwise be acquired.
sourcepub fn try_lock(&self) -> Option<ReentrantMutexGuard<'_, T>>
pub fn try_lock(&self) -> Option<ReentrantMutexGuard<'_, T>>
Attempts to acquire this lock.
If the lock could not be acquired at this time, then Err
is returned.
Otherwise, an RAII guard is returned.
This function does not block.
Errors
If another user of this mutex panicked while holding the mutex, then this call will return failure if the mutex would otherwise be acquired.