rust - 使用自旋锁和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`
有什么办法可以解决吗?
解决方案
从您在此处显示的节略代码来看,移入Mutex
IDT 类型将完成这项工作:
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 的机会的额外好处。
推荐阅读
- angular - 如何将数据 + 多个文件从 Angular 上传到 .net core Web Api
- css - 关键帧的混合
- ruby - Ruby On Rails - 新的迁移和模型更改导致迁移失败
- javascript - 等待由不同组件触发的 2 个 API 完成,然后再触发另一个 API
- r - 列在 num 时错误地标记为 int
- c# - CountdownEvent 与 Barrier 的多线程用法?
- c++11 - 英特尔 C++ 编译器无法选择模板函数重载
- apache-spark - 如何将spark与多个cassandra主机和不同表的访问结合起来处理不同的方法
- html - 如何让我的选项表在移动设备上每个都 100% 宽度?
- php - 如果记录存在 2 列的值,则忽略插入