为什么在尝试创建已经存在的元素时保护全球独特的实例僵局的静音?

问题描述 投票:0回答:1

这个程序挂起,我怀疑它不会像预定的那样释放Mutex锁。我一定在这里做错了什么,但是我不能把我的手指放在上面。

use std::any::TypeId; use std::collections::HashSet; use std::marker::PhantomData; use std::sync::{LazyLock, Mutex}; use unique::Unique; static ID_SET: LazyLock<Mutex<HashSet<TypeId>>> = LazyLock::new(|| Mutex::new(HashSet::new())); mod unique { use super::*; // Due to its private data member, outside this module, // this struct can only be created using `new`. pub struct Unique<O: 'static>(PhantomData<O>); impl<O: 'static> Unique<O> { pub fn id() -> TypeId { TypeId::of::<O>() } pub fn new() -> Option<Self> { let mut set = ID_SET.lock().unwrap(); dbg!(set.insert(Self::id())).then_some(Self(PhantomData)) } } impl<O: 'static> Drop for Unique<O> { fn drop(&mut self) { let mut set = ID_SET.lock().unwrap(); (!set.remove(&Self::id())).then(|| panic!("duplicity detected")); } } } fn main() { struct TheOneRing; let the_one_ring = Unique::<TheOneRing>::new().unwrap(); let the_two_ring = Unique::<TheOneRing>::new().unwrap(); panic!(); }
Prints:

[src/main.rs:24:13] set.insert(Self::id()) = true [src/main.rs:24:13] set.insert(Self::id()) = false
但然后悬挂...

rust mutex deadlock
1个回答
5
投票
我在这里一定做错了,但是我不能把我的手指放在上面。

pub fn new() -> Option<Self> { let mut set = ID_SET.lock().unwrap(); dbg!(set.insert(Self::id())).then_some(Self(PhantomData)) }
then_some

渴望,所以这有效

    pub fn new() -> Option<Self> {
        let mut set = ID_SET.lock().unwrap();
        let v = Self(PhantomData);
        dbg!(set.insert(Self::id())).then_some(v);
    }

表示如果返回
set.insert

false

,thove thoved thoved throp tove toge of the thot throud thot thot thot like lock the Lock,但该锁已经由
v
持有,因此僵持
    

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.