Re: [TECH TOPIC] Rust for Linux

Jan Kara
2021-07-07T20:38:35Z

On Wed 07-07-21 20:19:19, Wedson Almeida Filho wrote:
<snip good explanations how refs work>

> There are real cases when you can't guarantee that lifetimes line up as required
> by the compiler to guarantee safety. In such cases, you can "clone" ptr (which
> increments the refcount, again from n to n+1, where n > 0), then you end up with
> your own reference to the underlying `X`, for example:
>
> fn main() {
> let ptr_clone;
> {
> let ptr = Ref::new(X { a: 10, b: 20 });
> ptr_clone = ptr.clone();
> }
> println!("{}", ptr_clone.a);
> }
>
> (Note that the reference owned by `ptr` has been destroyed by the time
> `ptr_clone.a` is used in `println`, but `ptr_clone` has its own reference due to
> the clone call.)
>
> The ideas above apply equally well if instead of thinking in terms of scope, you
> think in terms of threads/CPUs. If a thread needs a refcounted object to
> potentially outlive the borrow keeping it alive, then it needs to increment
> the refcount: if you can't prove the lifetime rules, then you must clone the
> reference.
>
> Given that by construction the refcount starts at 1, there is no path to go from
> 0 to 1. Ever.
>
> Where would a lock be needed in the examples above?

So I think Greg speaks about a situation where you have multiple threads
and the refcounted object can be looked up through some structure all the
threads see. And the problem is that the shared data structure cannot hold
ref to the object it points to because you want to detect the situation
where the data structure is the only place pointing to the object and
reclaim the object in that case. Currently I don't see how to model this
idiom with Rust refs.

Honza
--
Jan Kara <jack@suse.com>
SUSE Labs, CR