pub struct Mutex<T: ?Sized> { /* private fields */ }
Expand description
A simple mutex.
This is mutual-exclusion primitive. It guarantees that only one thread at a time may access the data it protects. When multiple threads attempt to lock the same mutex, only one at a time is allowed to progress, the others will block (sleep) until the mutex is unlocked, at which point another thread will be allowed to wake up and make progress.
Examples
struct Example {
a: u32,
b: u32,
}
static EXAMPLE: Mutex<Example> = Mutex::new(Example { a: 10, b: 20 });
fn inc_a(example: &Mutex<Example>) {
let mut guard = example.lock();
guard.a += 1;
}
fn sum(example: &Mutex<Example>) -> u32 {
let guard = example.lock();
guard.a + guard.b
}
fn try_new(a: u32, b: u32) -> Result<Ref<Mutex<Example>>> {
Ref::try_new(Mutex::new(Example { a, b }))
}
assert_eq!(EXAMPLE.lock().a, 10);
assert_eq!(sum(&EXAMPLE), 30);
inc_a(&EXAMPLE);
assert_eq!(EXAMPLE.lock().a, 11);
assert_eq!(sum(&EXAMPLE), 31);
Implementations
Trait Implementations
sourceimpl<T: ?Sized> Lock<WriteLock> for Mutex<T>
impl<T: ?Sized> Lock<WriteLock> for Mutex<T>
type Inner = T
type Inner = T
The type of the data protected by the lock.
type GuardContext = EmptyGuardContext
type GuardContext = EmptyGuardContext
The type of context, if any, that needs to be stored in the guard.
sourcefn lock_noguard(&self) -> EmptyGuardContext
fn lock_noguard(&self) -> EmptyGuardContext
Acquires the lock, making the caller its owner.
sourceunsafe fn unlock(&self, _: &mut EmptyGuardContext)
unsafe fn unlock(&self, _: &mut EmptyGuardContext)
Releases the lock, giving up ownership of the lock. Read more
sourcefn locked_data(&self) -> &UnsafeCell<T>
fn locked_data(&self) -> &UnsafeCell<T>
Returns the data protected by the lock.
sourcefn relock(&self, ctx: &mut Self::GuardContext)
fn relock(&self, ctx: &mut Self::GuardContext)
Reacquires the lock, making the caller its owner. Read more
sourceimpl<T> LockFactory for Mutex<T>
impl<T> LockFactory for Mutex<T>
sourceimpl<T> LockIniter for Mutex<T>
impl<T> LockIniter for Mutex<T>
impl<T: ?Sized + Send> Send for Mutex<T>
impl<T: ?Sized + Send> Sync for Mutex<T>
Auto Trait Implementations
impl<T> !RefUnwindSafe for Mutex<T>
impl<T: ?Sized> Unpin for Mutex<T> where
T: Unpin,
impl<T> !UnwindSafe for Mutex<T>
Blanket Implementations
sourceimpl<T> BorrowMut<T> for T where
T: ?Sized,
impl<T> BorrowMut<T> for T where
T: ?Sized,
const: unstable · sourcefn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more
sourceimpl<L> NeedsLockClass for L where
L: LockIniter,
impl<L> NeedsLockClass for L where
L: LockIniter,
sourcefn init(
self: Pin<&mut L>,
name: &'static CStr,
key: &'static LockClassKey,
&'static LockClassKey
)
fn init(
self: Pin<&mut L>,
name: &'static CStr,
key: &'static LockClassKey,
&'static LockClassKey
)
Initialises the type instance so that it can be safely used. Read more