pub struct Mutex<T: ?Sized> { /* private fields */ }
nonpoison_mutex #134645)
A mutual exclusion primitive useful for protecting shared data that does not keep track of lock poisoning.
For more information about mutexes, check out the documentation for the poisoning variant of this lock at poison::Mutex.
Note that this Mutex does not propagate threads that panic while holding the lock via poisoning. If you need this functionality, see poison::Mutex.
#![feature(nonpoison_mutex)]
use std::thread;
use std::sync::{Arc, nonpoison::Mutex};
let mutex = Arc::new(Mutex::new(0u32));
let mut handles = Vec::new();
for n in 0..10 {
let m = Arc::clone(&mutex);
let handle = thread::spawn(move || {
let mut guard = m.lock();
*guard += 1;
panic!("panic from thread {n} {guard}")
});
handles.push(handle);
}
for h in handles {
let _ = h.join();
}
println!("Finished, locked {} times", mutex.lock());impl<T> Mutex<T>
pub const fn new(t: T) -> Mutex<T>
nonpoison_mutex #134645)
Creates a new mutex in an unlocked state ready for use.
#![feature(nonpoison_mutex)] use std::sync::nonpoison::Mutex; let mutex = Mutex::new(0);
pub fn get_cloned(&self) -> Twhere
T: Clone,lock_value_accessors #133407)
Returns the contained value by cloning it.
#![feature(nonpoison_mutex)] #![feature(lock_value_accessors)] use std::sync::nonpoison::Mutex; let mut mutex = Mutex::new(7); assert_eq!(mutex.get_cloned(), 7);
pub fn set(&self, value: T)
lock_value_accessors #133407)
Sets the contained value.
#![feature(nonpoison_mutex)] #![feature(lock_value_accessors)] use std::sync::nonpoison::Mutex; let mut mutex = Mutex::new(7); assert_eq!(mutex.get_cloned(), 7); mutex.set(11); assert_eq!(mutex.get_cloned(), 11);
pub fn replace(&self, value: T) -> T
lock_value_accessors #133407)
Replaces the contained value with value, and returns the old contained value.
#![feature(nonpoison_mutex)] #![feature(lock_value_accessors)] use std::sync::nonpoison::Mutex; let mut mutex = Mutex::new(7); assert_eq!(mutex.replace(11), 7); assert_eq!(mutex.get_cloned(), 11);
impl<T: ?Sized> Mutex<T>
pub fn lock(&self) -> MutexGuard<'_, T>
nonpoison_mutex #134645)
Acquires a mutex, blocking the current thread until it is able to do so.
This function will block the local thread until it is available to acquire the mutex. Upon returning, the thread is the only thread with the lock held. An RAII guard is returned to allow scoped unlock of the lock. When the guard goes out of scope, the mutex will be unlocked.
The exact behavior on locking a mutex in the thread which already holds the lock is left unspecified. However, this function will not return on the second call (it might panic or deadlock, for example).
This function might panic when called if the lock is already held by the current thread.
#![feature(nonpoison_mutex)]
use std::sync::{Arc, nonpoison::Mutex};
use std::thread;
let mutex = Arc::new(Mutex::new(0));
let c_mutex = Arc::clone(&mutex);
thread::spawn(move || {
*c_mutex.lock() = 10;
}).join().expect("thread::spawn failed");
assert_eq!(*mutex.lock(), 10);pub fn try_lock(&self) -> TryLockResult<MutexGuard<'_, T>>
nonpoison_mutex #134645)
Attempts to acquire this lock.
This function does not block. If the lock could not be acquired at this time, then WouldBlock is returned. Otherwise, an RAII guard is returned.
The lock will be unlocked when the guard is dropped.
If the mutex could not be acquired because it is already locked, then this call will return the WouldBlock error.
use std::sync::{Arc, Mutex};
use std::thread;
let mutex = Arc::new(Mutex::new(0));
let c_mutex = Arc::clone(&mutex);
thread::spawn(move || {
let mut lock = c_mutex.try_lock();
if let Ok(ref mut mutex) = lock {
**mutex = 10;
} else {
println!("try_lock failed");
}
}).join().expect("thread::spawn failed");
assert_eq!(*mutex.lock().unwrap(), 10);pub fn into_inner(self) -> Twhere
T: Sized,nonpoison_mutex #134645)
Consumes this mutex, returning the underlying data.
#![feature(nonpoison_mutex)] use std::sync::nonpoison::Mutex; let mutex = Mutex::new(0); assert_eq!(mutex.into_inner(), 0);
pub fn get_mut(&mut self) -> &mut T
nonpoison_mutex #134645)
Returns a mutable reference to the underlying data.
Since this call borrows the Mutex mutably, no actual locking needs to take place β the mutable borrow statically guarantees no locks exist.
#![feature(nonpoison_mutex)] use std::sync::nonpoison::Mutex; let mut mutex = Mutex::new(0); *mutex.get_mut() = 10; assert_eq!(*mutex.lock(), 10);
pub const fn data_ptr(&self) -> *mut T
mutex_data_ptr #140368)
Returns a raw pointer to the underlying data.
The returned pointer is always non-null and properly aligned, but it is the userβs responsibility to ensure that any reads and writes through it are properly synchronized to avoid data races, and that it is not read or written through after the mutex is dropped.
pub fn with_mut<F, R>(&self, f: F) -> Rwhere
F: FnOnce(&mut T) -> R,lock_value_accessors #133407)
Acquires the mutex and provides mutable access to the underlying data by passing a mutable reference to the given closure.
This method acquires the lock, calls the provided closure with a mutable reference to the data, and returns the result of the closure. The lock is released after the closure completes, even if it panics.
#![feature(lock_value_accessors, nonpoison_mutex)]
use std::sync::nonpoison::Mutex;
let mutex = Mutex::new(2);
let result = mutex.with_mut(|data| {
*data += 3;
*data + 5
});
assert_eq!(*mutex.lock(), 5);
assert_eq!(result, 10);impl<T: ?Sized + Debug> Debug for Mutex<T>
fn fmt(&self, f: &mut Formatter<'_>) -> Result
impl<T: ?Sized + Default> Default for Mutex<T>
fn default() -> Mutex<T>
Creates a Mutex<T>, with the Default value for T.
impl<T> From<T> for Mutex<T>
fn from(t: T) -> Self
Creates a new mutex in an unlocked state ready for use. This is equivalent to Mutex::new.
impl<T: ?Sized + Send> Send for Mutex<T>T must be Send for a Mutex to be Send because it is possible to acquire the owned T from the Mutex via into_inner.
impl<T: ?Sized + Send> Sync for Mutex<T>T must be Send for Mutex to be Sync. This ensures that the protected data can be accessed safely from multiple threads without causing data races or other unsafe behavior.
Mutex<T> provides mutable access to T to one thread at a time. However, itβs essential for T to be Send because itβs not safe for non-Send structures to be accessed in this manner. For instance, consider Rc, a non-atomic reference counted smart pointer, which is not Send. With Rc, we can have multiple copies pointing to the same heap allocation with a non-atomic reference count. If we were to use Mutex<Rc<_>>, it would only protect one instance of Rc from shared access, leaving other copies vulnerable to potential data races.
Also note that it is not necessary for T to be Sync as &T is only made available to one thread at a time if T is not Sync.
impl<T> !Freeze for Mutex<T>
impl<T> !RefUnwindSafe for Mutex<T>
impl<T> Unpin for Mutex<T>where
T: Unpin + ?Sized,impl<T> UnwindSafe for Mutex<T>where
T: UnwindSafe + ?Sized,impl<T> Any for Twhere
T: 'static + ?Sized,impl<T> Borrow<T> for Twhere
T: ?Sized,impl<T> BorrowMut<T> for Twhere
T: ?Sized,impl<T> From<!> for T
fn from(t: !) -> T
impl<T> From<T> for T
fn from(t: T) -> T
Returns the argument unchanged.
impl<T, U> Into<U> for Twhere
U: From<T>,fn into(self) -> U
Calls U::from(self).
That is, this conversion is whatever the implementation of From<T> for U chooses to do.
impl<T, U> TryFrom<U> for Twhere
U: Into<T>,type Error = Infallible
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
impl<T, U> TryInto<U> for Twhere
U: TryFrom<T>,
Β© 2010 The Rust Project Developers
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.
https://doc.rust-lang.org/std/sync/nonpoison/struct.Mutex.html