pub struct MutexGuard<'a, T: ?Sized> { /* private fields */ }展开描述
持有的 的句柄。由于实现了 Mutex,可以在任意 Send 点持有该 guard。.await
只要你持有
此 guard,
就拥有对底层
的独占访问权。
guard 内部
借用
T,
因此
只要 guard 存在,
mutex
就不会被丢弃。Mutex
无论
guard
何时
被丢弃,
lock
都会
自动释放,
此时
将
再次成功。lock
实现§
Source§impl<'a, T: ?Sized> MutexGuard<'a, T>
impl<'a, T: ?Sized> MutexGuard<'a, T>
Sourcepub fn map<U, F>(this: Self, f: F) -> MappedMutexGuard<'a, U>
pub fn map<U, F>(this: Self, f: F) -> MappedMutexGuard<'a, U>
为已锁定数据的一个组件创建一个新的 。MappedMutexGuard
该操作不会失败,因为传入的 已经锁定了这个互合。MutexGuard
这是一个关联函数,需要作为 使用。如果用方法会和已锁定数据内容器上同名的方法冲突。MutexGuard::map(...)
§示例
use tokio::sync::{Mutex, MutexGuard};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Foo(u32);
let foo = Mutex::new(Foo(1));
{
let mut mapped = MutexGuard::map(foo.lock().await, |f| &mut f.0);
*mapped = 2;
}
assert_eq!(Foo(2), *foo.lock().await);Sourcepub fn try_map<U, F>(this: Self, f: F) -> Result<MappedMutexGuard<'a, U>, Self>
pub fn try_map<U, F>(this: Self, f: F) -> Result<MappedMutexGuard<'a, U>, Self>
尝试为已锁定数据的一个组件创建一个新的 。如果闭包返回 MappedMutexGuard,则返回原始的 guard。None
该操作不会失败,因为传入的 已经锁定了这个互合。MutexGuard
这是一个关联函数,需要作为 使用。如果用方法会和已锁定数据内容器上同名的方法冲突。MutexGuard::try_map(...)
§示例
use tokio::sync::{Mutex, MutexGuard};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Foo(u32);
let foo = Mutex::new(Foo(1));
{
let mut mapped = MutexGuard::try_map(foo.lock().await, |f| Some(&mut f.0))
.expect("should not fail");
*mapped = 2;
}
assert_eq!(Foo(2), *foo.lock().await);Sourcepub fn mutex(this: &Self) -> &'a Mutex<T>
pub fn mutex(this: &Self) -> &'a Mutex<T>
返回原始 的引用。Mutex
use tokio::sync::{Mutex, MutexGuard};
async fn unlock_and_relock<'l>(guard: MutexGuard<'l, u32>) -> MutexGuard<'l, u32> {
println!("1. contains: {:?}", *guard);
let mutex = MutexGuard::mutex(&guard);
drop(guard);
let guard = mutex.lock().await;
println!("2. contains: {:?}", *guard);
guard
}Trait 实现§
Source§impl<T: ?Sized> Deref for MutexGuard<'_, T>
impl<T: ?Sized> Deref for MutexGuard<'_, T>
Source§impl<T: ?Sized> DerefMut for MutexGuard<'_, T>
impl<T: ?Sized> DerefMut for MutexGuard<'_, T>
impl<T> Sync for MutexGuard<'_, T>
自动 Trait 实现§
impl<'a, T> Freeze for MutexGuard<'a, T>where
T: ?Sized,
impl<'a, T> !RefUnwindSafe for MutexGuard<'a, T>
impl<'a, T> Send for MutexGuard<'a, T>
impl<'a, T> Unpin for MutexGuard<'a, T>where
T: ?Sized,
impl<'a, T> UnsafeUnpin for MutexGuard<'a, T>where
T: ?Sized,
impl<'a, T> !UnwindSafe for MutexGuard<'a, T>
Blanket 实现§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. 更多信息