Re: [TECH TOPIC] Rust for Linux

Miguel Ojeda
2021-07-07T20:58:57Z

On Wed, Jul 7, 2021 at 7:20 PM Greg KH <greg@kroah.com> wrote:
>
> That's not what I meant by bringing up a kref. I was trying to ask
> where the "real" lock here is. It has to be somewhere...

Given this sentence, I think I understand where the confusion comes
from. The key is that `Ref` (`Arc`) is not adding any thread-safety to
the `T` it wraps -- it is only concerned about providing
reference-counting semantics.

For that it only needs to keep a thread-safe refcount for a given `T`.
But the `T` might be (or not!) thread-safe. Since the refcount is an
atomic, that is enough for implementing `Ref<T>`, no locks are needed.

Now, if you need mutable access to the content of an `Ref<T>` that is
shared by several threads at the same time, you need something extra
-- that is where you would need a lock. For instance, in normal Rust
code you may see a `Arc<Mutex<T>>` being used.

The big thing is that if you get any of this wrong, you get a
compile-time error. For instance, if you create a `Ref<T>` out of a
`T` that is not marked as safe to be sent across threads, you get an
error when you try to send the `Ref`. Or if you create a `Ref<T>` and
try to call a method that mutates the `T` across threads, you will
also get a compile-time error. Thus you cannot forget to have a lock
if it is needed.

Cheers,
Miguel