pub struct Guard<'a> { /* private fields */ }Expand description
An acquired lock guard.
This object is created by calling Lock::lock or one of the other locking
functions.
A Guard can be used to access Locked data by calling Locked::get.
Each Guard represents a ticket of the Lock it was created from. A thread can
have any number of tickets and while a thread holds at least 1 ticket of a Lock,
no other thread can acquire a ticket from that Lock.
A Guard can temporarily give up its ticket by calling Guard::unlocked or
Guard::unlocked_fair. The ticket will be restored before those functions return.
The Guard is inaccessible while the function is running.
Dropping the Guard or calling Guard::unlock_fair consumes the ticket.
The Guard can be passed to mem::forget to leak the ticket without leaking any
memory.
§Example
use shared_lock::Lock;
let lock = Lock::default();
let _guard = lock.lock();Implementations§
Source§impl Guard<'_>
impl Guard<'_>
Sourcepub fn unlock_fair(self)
pub fn unlock_fair(self)
Unlocks this guard.
If this causes the number of tickets to drop to 0, the underlying mutex is unlocked using a fair protocol.
§Example
use shared_lock::Lock;
let lock = Lock::default();
let guard = lock.lock();
guard.unlock_fair();Sourcepub fn unlocked<T>(&mut self, f: impl FnOnce() -> T) -> T
pub fn unlocked<T>(&mut self, f: impl FnOnce() -> T) -> T
Unlocks this guard, runs a function, and then re-acquires the guard.
If another guard exists, then other threads will not be able to acquire the lock even while the function is running.
§Example
use shared_lock::Lock;
let lock = Lock::default();
let locked = lock.wrap(1);
let mut guard = lock.lock();
assert_eq!(*locked.get(&guard), 1);
guard.unlocked(|| {
assert!(!lock.is_locked());
});
assert_eq!(*locked.get(&guard), 1);Sourcepub fn unlocked_fair<T>(&mut self, f: impl FnOnce() -> T) -> T
pub fn unlocked_fair<T>(&mut self, f: impl FnOnce() -> T) -> T
Unlocks this guard fairly, runs a function, and then re-acquires the guard.
If another guard exists, then other threads will not be able to acquire the lock even while the function is running.
§Example
use shared_lock::Lock;
let lock = Lock::default();
let locked = lock.wrap(1);
let mut guard = lock.lock();
assert_eq!(*locked.get(&guard), 1);
guard.unlocked_fair(|| {
assert!(!lock.is_locked());
});
assert_eq!(*locked.get(&guard), 1);