asterinas icon indicating copy to clipboard operation
asterinas copied to clipboard

Improve shared locks (`Arc<*Lock>`) by allowing dynamically borrowed lock guards

Open junyang-zh opened this issue 10 months ago • 4 comments

Assume that we have such code:

struct Foo {
    bar: Arc<SpinLock<Bar>>
}
impl Foo {
    fn get_bar_guard(&self) -> SpinLockGuard<'_, Bar> {
        self.bar.lock()
    }
}

It won't compile since SpinLockGuard has a reference to the lock and the lifetime need to be statically checked.

This PR might improve the situation. But we might end up writing all implementations twice since https://github.com/rust-lang/rust/issues/124225 is unusable currently. Otherwise heavy proc macros are needed to reuse code.

This feature is a must for #713. I suggest to implement Arc version of guards for methods that are needed.

junyang-zh avatar Apr 22 '24 17:04 junyang-zh

#713 Chooses to be based upon this. Successfully merging that first will close this PR.

junyang-zh avatar Apr 23 '24 01:04 junyang-zh

@junyang-zh This is a reasonable feature for our lock implementation. But the solution is not as elegant as I thought it could be.

impl<'a, T: ?Sized> Mutex<T> {
    /// The same as [`lock`], but allow dynamic borrow rules.
    pub fn lock_arc(self: &Arc<Self>) -> ArcMutexGuard<T> {
        self.queue.wait_until(|| self.try_lock_arc())
    }
}

Adding this lock_arc method looks ugly. The Rust std's Mutex does not have a counterpart. Why can't we do the same?

tatetian avatar Apr 26 '24 04:04 tatetian

The Rust std's Mutex does not have a counterpart.

Just FYI, they are not in the Rust's standard library (yet), but parking_lot has Mutex::lock_arc and tokio has Mutex::lock_owned.

lrh2000 avatar Apr 26 '24 04:04 lrh2000

The Rust std's Mutex does not have a counterpart.

Just FYI, they are not in the Rust's standard library (yet), but parking_lot has Mutex::lock_arc and tokio has Mutex::lock_owned.

I see. Thanks for the explanation!

tatetian avatar Apr 26 '24 09:04 tatetian