Re: [PATCH 2/3] rust: sync: add SetOnce::try_get_or_populate()

Boqun Feng <[email protected]> Wed, 29 Jul 2026 07:23:57 -0700
Newsgroups org.kernel.vger.linux-modules,org.kernel.vger.linux-kernel,org.kernel.vger.rust-for-linux
Message-ID <[email protected]>
On Wed, Jul 29, 2026 at 11:05:55PM +0900, Alexandre Courbot wrote:
[...]
> > +    /// Get the value, or populate it if it's missing.
> > +    ///
> > +    /// This method is useful to avoid spinning on the internal atomic state. If all writers call
> > +    /// this method with the same lock, then they are synchronized with each other and it's
> > +    /// guaranteed that no caller will attempt to invoke [`SetOnce::populate`] more than once.
> > +    pub fn try_get_or_populate<F, E, U, B>(&self, lock: &lock::Lock<U, B>, f: F) -> Result<&T, E>
> 
> From the API perspective, this still leaves the option of calling the
> method concurrently with different locks. What happens in this case?
> 

Calling this function with different locks is not a correctness issue
(SetOnce::populate() already handle the synchronization). User may want
to synchronize different groups of writers with different locks.

Regards,
Boqun

> > +    where
> > +        B: lock::Backend,
> > +        F: FnOnce() -> Result<T, E>,
> > +    {
> > +        if let Some(value) = self.as_ref() {
> > +            return Ok(value);
> > +        }
> > +
> > +        let mut to_insert = f()?;
[...]