0

I was trying to create a mutable struct (an interrupt descriptor table) with s static lifetime. Since the static mut is not safe, I use an alternative of lazy_static and mutex like this

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

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

My 'idt_type' has a method which takes a static self as perameter like this:

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

However is I try to use this method like this

IDT.lock().load();

the complier will complain since lock() returns a non static 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`

Is there any way to work around?

2
  • Why would the type take a &'static self rather than &'a self? The mutex won't ever given you a 'static reference as that would imply you have locked the data forever, and thus don't need a mutex. Commented Jan 5, 2020 at 1:46
  • This is a function in a public crate. The function of the load() is to load the address of idt into the reg, and the idt should have a static lifetime. Anyway, I'm trying to find an alternative for static mut Commented Jan 5, 2020 at 2:56

1 Answer 1

4

Judging from the abridged code you showed here, moving Mutex inside the IDT type will do the job:

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();
}

It is now your responsibility to implement the locking logic correctly instead of users of your crate. So it also has the added benefit of reducing the chance of misusing the API.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.