首页 > 解决方案 > 使用自旋锁和lazy_static!在静态结构上

问题描述

我试图创建一个具有静态生命周期的可变结构(一个中断描述符表)。由于static mut不安全,我使用了这样的lazy_static和mutex的替代方法

use lazy_static::lazy_static;
use spin::Mutex;

lazy_static! {
    pub static ref IDT: Mutex<idt_type> = Mutex::new(...);
}

我的 'idt_type' 有一个方法,它采用静态自我作为参数,如下所示:

impl idt_type {
    pub fn load(&'static self);
}

但是我是否尝试像这样使用这种方法

IDT.lock().load();

编译器会抱怨,因为 lock() 返回一个非静态 MutexGuard:

         IDT.lock().load();
   |     ^^^^^^^^^^-------- temporary value is freed at the end of this statement
   |     |
   |     creates a temporary which is freed while still in use
   |     argument requires that borrow lasts for `'static`

有什么办法可以解决吗?

标签: rust

解决方案


从您在此处显示的节略代码来看,移入MutexIDT 类型将完成这项工作:

use lazy_static::lazy_static;
use spin::Mutex;

lazy_static! {
    pub static ref IDT: IdtType = IdtType(Mutex::new(0));
}

pub struct IdtType(Mutex<i32>);

impl IdtType {
    pub fn load(&'static self) {
        self.0.lock();
    }
}

fn main() {
    IDT.load();
}

现在你有责任正确地实现锁定逻辑,而不是你的 crate 的用户。因此,它还具有减少滥用 API 的机会的额外好处。


推荐阅读