pub struct MutexGuard<'a, T: ?Sized> { /* 私有字段 */ }展开描述
对持有 Mutex 的句柄。该 guard 可以跨越任何 .await 点,因为它实现了 Send。
只要你拥有此 guard,你就可以独占访问底层的 T。该 guard 在内部借用 Mutex,因此只要 guard 存在,mutex 就不会被 drop。
每当守卫被 drop 时,锁会自动释放,此时 lock 将再次成功。
实现§
源代码§impl<'a, T: ?Sized> MutexGuard<'a, T>
impl<'a, T: ?Sized> MutexGuard<'a, T>
源代码pub 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);源代码pub 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。如果闭包返回 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);源代码pub 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 实现§
源代码§impl<T: ?Sized> Deref for MutexGuard<'_, T>
impl<T: ?Sized> Deref for MutexGuard<'_, T>
源代码§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 实现§
源代码§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
源代码§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. 更多信息