pub struct Mutex<T: ?Sized> { /* fields omitted */ }
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.
let mtx = Mutex::<u32>::new(0);
let fut = mtx.lock().map(|mut guard| { *guard += 5; });
spawn(fut).wait_future();
assert_eq!(mtx.try_unwrap().unwrap(), 5);
Create a new Mutex
in the unlocked state.
Consumes the Mutex
and returns the wrapped data. If the Mutex
still
has multiple references (not necessarily locked), returns a copy of
self
instead.
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.
let mut mtx = Mutex::<u32>::new(0);
*mtx.get_mut().unwrap() += 5;
assert_eq!(mtx.try_unwrap().unwrap(), 5);
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.
Attempts to acquire the lock.
If the operation would block, returns Err
instead. Otherwise, returns
a guard (not a Future
).
let mut mtx = Mutex::<u32>::new(0);
match mtx.try_lock() {
Ok(mut guard) => *guard += 5,
Err(()) => println!("Better luck next time!")
};
Formats the value using the given formatter. Read more
Performs copy-assignment from source
. Read more