Struct Mutex

Source
pub struct Mutex<T: ?Sized> { /* private fields */ }
Expand description

A Futures-aware Mutex.

std::sync::Mutex cannot be used in an asynchronous environment like Tokio, because a mutex acquisition can block an entire reactor. This class can be used instead. It functions much like std::sync::Mutex. Unlike that class, it also has a builtin Arc, making it accessible from multiple threads. It’s also safe to clone. Also unlike std::sync::Mutex, this class does not detect lock poisoning.

§Examples

let mtx = Mutex::<u32>::new(0);
let fut = mtx.lock().map(|mut guard| { *guard += 5; });
block_on(fut);
assert_eq!(mtx.try_unwrap().unwrap(), 5);

Implementations§

Source§

impl<T> Mutex<T>

Source

pub fn new(t: T) -> Mutex<T>

Create a new Mutex in the unlocked state.

Source

pub fn try_unwrap(self) -> Result<T, Mutex<T>>

Consumes the Mutex and returns the wrapped data. If the Mutex still has multiple references (not necessarily locked), returns a copy of self instead.

Source§

impl<T: ?Sized> Mutex<T>

Source

pub fn downgrade(this: &Mutex<T>) -> MutexWeak<T>

Create a MutexWeak reference to this Mutex.

Source

pub fn get_mut(&mut self) -> Option<&mut T>

Returns a reference to the underlying data, if there are no other clones of the Mutex.

Since this call borrows the Mutex mutably, no actual locking takes place – the mutable borrow statically guarantees no locks exist. However, if the Mutex has already been cloned, then None will be returned instead.

§Examples
let mut mtx = Mutex::<u32>::new(0);
*mtx.get_mut().unwrap() += 5;
assert_eq!(mtx.try_unwrap().unwrap(), 5);
Source

pub fn lock(&self) -> MutexFut<T>

Acquires a Mutex, blocking the task in the meantime. When the returned Future is ready, this task will have sole access to the protected data.

Source

pub fn try_lock(&self) -> Result<MutexGuard<T>, TryLockError>

Attempts to acquire the lock.

If the operation would block, returns Err instead. Otherwise, returns a guard (not a Future).

§Examples
let mut mtx = Mutex::<u32>::new(0);
match mtx.try_lock() {
    Ok(mut guard) => *guard += 5,
    Err(_) => println!("Better luck next time!")
};
Source

pub fn ptr_eq(this: &Mutex<T>, other: &Mutex<T>) -> bool

Returns true if the two Mutex point to the same data else false.

Source§

impl<T: 'static + ?Sized> Mutex<T>

Source

pub fn with<B, F, R>(&self, f: F) -> impl Future<Output = R>
where F: FnOnce(MutexGuard<T>) -> B + Send + 'static, B: Future<Output = R> + Send + 'static, R: Send + 'static, T: Send,

Available on crate feature tokio only.

Acquires a Mutex and performs a computation on its guarded value in a separate task. Returns a Future containing the result of the computation.

When using Tokio, this method will often hold the Mutex for less time than chaining a computation to lock. The reason is that Tokio polls all tasks promptly upon notification. However, Tokio does not guarantee that it will poll all futures promptly when their owning task gets notified. So it’s best to hold Mutexes within their own tasks, lest their continuations get blocked by slow stacked combinators.

§Examples
let mtx = Mutex::<u32>::new(0);
let mut rt = Runtime::new().unwrap();
rt.block_on(async {
    mtx.with(|mut guard| {
        *guard += 5;
        ready::<()>(())
    }).await
});
assert_eq!(mtx.try_unwrap().unwrap(), 5);
Source

pub fn with_local<B, F, R>(&self, f: F) -> impl Future<Output = R>
where F: FnOnce(MutexGuard<T>) -> B + 'static, B: Future<Output = R> + 'static + Unpin, R: 'static,

Available on crate feature tokio only.

Like with but for Futures that aren’t Send. Spawns a new task on a single-threaded Runtime to complete the Future.

§Examples
// Note: Rc is not `Send`
let mtx = Mutex::<Rc<u32>>::new(Rc::new(0));
let mut rt = Runtime::new().unwrap();
rt.block_on(async {
    mtx.with_local(|mut guard| {
        *Rc::get_mut(&mut *guard).unwrap() += 5;
        ready(())
    }).await
});
assert_eq!(*mtx.try_unwrap().unwrap(), 5);

Trait Implementations§

Source§

impl<T: ?Sized> Clone for Mutex<T>

Source§

fn clone(&self) -> Mutex<T>

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<T: Debug + ?Sized> Debug for Mutex<T>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<T: Default + ?Sized> Default for Mutex<T>

Source§

fn default() -> Mutex<T>

Returns the “default value” for a type. Read more
Source§

impl<T: ?Sized + Send> Send for Mutex<T>

Source§

impl<T: ?Sized + Send> Sync for Mutex<T>

Auto Trait Implementations§

§

impl<T> Freeze for Mutex<T>
where T: ?Sized,

§

impl<T> !RefUnwindSafe for Mutex<T>

§

impl<T> Unpin for Mutex<T>
where T: ?Sized,

§

impl<T> !UnwindSafe for Mutex<T>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.