pub struct Mutex<T: ?Sized> { /* private fields */ }Expand description
A mutex grants synchronized access to a value
§Example
use syncrs::Mutex;
use std::sync::Arc;
let n = Arc::new(Mutex::new(0));
let threads = (0..10).map(|_|{
let c = Arc::clone(&n);
std::thread::spawn(move || {
let mut sync_n = c.lock();
for _ in 0..10 {
*sync_n += 1;
}
})
}).collect::<Vec<_>>();
for t in threads {
t.join().unwrap();
}
assert_eq!(*n.lock(), 100);Implementations§
Source§impl<T> Mutex<T>
impl<T> Mutex<T>
Sourcepub fn into_inner(self) -> T
pub fn into_inner(self) -> T
Consumes self and returns the inner T value
§Safety
Since we take self by value, we don’t need to
synchronize the access.
Source§impl<T: ?Sized> Mutex<T>
impl<T: ?Sized> Mutex<T>
Sourcepub fn try_lock(&self) -> Option<MutexGuard<'_, T>>
pub fn try_lock(&self) -> Option<MutexGuard<'_, T>>
Returns a lock guard for self, if it is
available.
If the operation whould’ve locked the execution, returns
None inmediately
The lock is held until the MutexGuard is dropped.
§Example
use syncrs::Mutex;
let mutex = Mutex::new(10);
let guard1 = mutex.lock();
// guard1 holds the lock
assert_eq!(mutex.try_lock(), None);
drop(guard1); // This frees the mutex
assert!(mutex.try_lock().is_some());Sourcepub fn lock(&self) -> MutexGuard<'_, T>
pub fn lock(&self) -> MutexGuard<'_, T>
Sourcepub const fn get_mut(&mut self) -> &mut T
pub const fn get_mut(&mut self) -> &mut T
Gets a mutable reference to the object.
§Safety
Since this function gets a mutable self reference,
we know the mutex is available.
The reference is statically guaranteed to be unique, so
we need not to worry about synchronization.
This is faster that spinlocking, and is 100% safe.
Trait Implementations§
impl<T: ?Sized + Send> Send for Mutex<T>
T must be Send for Mutex<T> to be Send
It’s possible to unwrap the Mutex into it’s inner
value (Mutex::into_inner). So we need to make sure
that T is Send.