Re: [PATCH v5] rust: add global lock support

From: Alice Ryhl
Date: Tue Oct 22 2024 - 08:46:55 EST


On Mon, Oct 21, 2024 at 5:23 PM Boqun Feng <boqun.feng@xxxxxxxxx> wrote:
>
> On Mon, Oct 21, 2024 at 01:17:23PM +0000, Alice Ryhl wrote:
> [...]
> > +///
> > +/// A global mutex used to protect all instances of a given struct.
> > +///
> > +/// ```
> > +/// # mod ex {
> > +/// # use kernel::prelude::*;
> > +/// kernel::sync::global_lock! {
> > +/// // SAFETY: Initialized in module initializer before first use.
> > +/// unsafe(uninit) static MY_MUTEX: Mutex<(), Guard = MyGuard, LockedBy = LockedByMyMutex> = ();
>
> Thanks! This looks much better now ;-)
>
> But I still want to get rid of "LockedBy=", so I've tried and seems it
> works, please see the below diff on top of your patch, I think it's
> better because:
>
> * Users don't to pick up the names for the locked_by type ;-)
> * It moves a significant amount of code out of macros.
> * By having:
>
> struct MyStruct {
> my_counter: GlobalLockedBy<MyGuard, u32>,
> }
>
> , it's much clear for users to see which guard is used to protected
> `my_counter`.
>
> I prefer this way. Any concern about doing this?

I think I came up with an even better way of doing it. The macro can
generate a dummy token type for the global lock, and then we can have
three types: GlobalLock<T>, GlobalGuard<T>, GlobalLockedBy<T> that are
all generic over the token type. The token type is an empty enum with
no contents, but implements an unsafe trait saying that there's only
one static using it.

This way we also do not need the helper module, as we no longer need
to generate a struct with private fields.

Alice