pub struct OwnedMutexGuard<T: ?Sized> { /* 私有字段 */ }展开描述
对持有 Mutex 的 owned 句柄。
此 guard 仅适用于包装在 Arc 中的 Mutex。它与 MutexGuard 相同,只是它不借用 Mutex,而是克隆 Arc,增加引用计数。这意味着与 MutexGuard 不同,它将具有 'static 生命周期。
只要你拥有此 guard,你就可以独占访问底层的 T。该 guard 在内部保持指向原始 Mutex 的引用计数指针,因此即使锁消失了,guard 仍然有效。
每当守卫被 drop 时,锁会自动释放,此时 lock 将再次成功。
实现§
源代码§impl<T: ?Sized> OwnedMutexGuard<T>
impl<T: ?Sized> OwnedMutexGuard<T>
源代码pub fn map<U, F>(this: Self, f: F) -> OwnedMappedMutexGuard<T, U>
pub fn map<U, F>(this: Self, f: F) -> OwnedMappedMutexGuard<T, U>
为已锁定数据的某个组件创建一个新的 OwnedMappedMutexGuard。
此操作不会失败,因为传入的 OwnedMutexGuard 已经锁定了互斥锁。
这是一个关联函数,需要用作 OwnedMutexGuard::map(...)。方法会与锁定数据内容上的同名方法冲突。
§示例
use tokio::sync::{Mutex, OwnedMutexGuard};
use std::sync::Arc;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Foo(u32);
let foo = Arc::new(Mutex::new(Foo(1)));
{
let mut mapped = OwnedMutexGuard::map(foo.clone().lock_owned().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<OwnedMappedMutexGuard<T, U>, Self>
pub fn try_map<U, F>( this: Self, f: F, ) -> Result<OwnedMappedMutexGuard<T, U>, Self>
尝试为已锁定数据的某个组件创建一个新的 OwnedMappedMutexGuard。如果闭包返回 None,则返回原始守卫。
此操作不会失败,因为传入的 OwnedMutexGuard 已经锁定了互斥锁。
这是一个关联函数,需要以 OwnedMutexGuard::try_map(...) 的方式使用。如果使用方法,将与已锁定数据内容上同名的方法产生冲突。
§示例
use tokio::sync::{Mutex, OwnedMutexGuard};
use std::sync::Arc;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Foo(u32);
let foo = Arc::new(Mutex::new(Foo(1)));
{
let mut mapped = OwnedMutexGuard::try_map(foo.clone().lock_owned().await, |f| Some(&mut f.0))
.expect("should not fail");
*mapped = 2;
}
assert_eq!(Foo(2), *foo.lock().await);源代码pub fn mutex(this: &Self) -> &Arc<Mutex<T>>
pub fn mutex(this: &Self) -> &Arc<Mutex<T>>
返回对原始 Arc<Mutex> 的引用。
use std::sync::Arc;
use tokio::sync::{Mutex, OwnedMutexGuard};
async fn unlock_and_relock(guard: OwnedMutexGuard<u32>) -> OwnedMutexGuard<u32> {
println!("1. contains: {:?}", *guard);
let mutex: Arc<Mutex<u32>> = OwnedMutexGuard::mutex(&guard).clone();
drop(guard);
let guard = mutex.lock_owned().await;
println!("2. contains: {:?}", *guard);
guard
}trait 实现§
源代码§impl<T: ?Sized> Deref for OwnedMutexGuard<T>
impl<T: ?Sized> Deref for OwnedMutexGuard<T>
源代码§impl<T: ?Sized> DerefMut for OwnedMutexGuard<T>
impl<T: ?Sized> DerefMut for OwnedMutexGuard<T>
impl<T> Sync for OwnedMutexGuard<T>
自动 trait 实现§
impl<T> Freeze for OwnedMutexGuard<T>where
T: ?Sized,
impl<T> !RefUnwindSafe for OwnedMutexGuard<T>
impl<T> Send for OwnedMutexGuard<T>
impl<T> Unpin for OwnedMutexGuard<T>where
T: ?Sized,
impl<T> UnsafeUnpin for OwnedMutexGuard<T>where
T: ?Sized,
impl<T> !UnwindSafe for OwnedMutexGuard<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. 更多信息