How do I create a global, mutable singleton?

前端 未结 3 1332
我在风中等你
我在风中等你 2020-11-21 06:59

What is the best way to create and use a struct with only one instantiation in the system? Yes, this is necessary, it is the OpenGL subsystem, and making multiple copies of

3条回答
  •  闹比i
    闹比i (楼主)
    2020-11-21 07:41

    Use SpinLock for global access.

    #[derive(Default)]
    struct ThreadRegistry {
        pub enabled_for_new_threads: bool,
        threads: Option>,
    }
    
    impl ThreadRegistry {
        fn threads(&mut self) -> &mut HashMap {
            self.threads.get_or_insert_with(HashMap::new)
        }
    }
    
    static THREAD_REGISTRY: SpinLock = SpinLock::new(Default::default());
    
    fn func_1() {
        let thread_registry = THREAD_REGISTRY.lock();  // Immutable access
        if thread_registry.enabled_for_new_threads {
        }
    }
    
    fn func_2() {
        let mut thread_registry = THREAD_REGISTRY.lock();  // Mutable access
        thread_registry.threads().insert(
            // ...
        );
    }
    

    If you want mutable state(NOT Singleton), see What Not to Do in Rust for more descriptions.

    Hope it's helpful.

提交回复
热议问题