Re: [PATCH] rust: sync: add lazy initialization methods to SetOnce
From: Alice Ryhl
Date: Mon Feb 16 2026 - 06:26:31 EST
On Mon, Feb 16, 2026 at 12:10:16PM +0100, Andreas Hindborg wrote:
> "Alice Ryhl" <aliceryhl@xxxxxxxxxx> writes:
>
> > On Sun, Feb 15, 2026 at 09:27:17PM +0100, Andreas Hindborg wrote:
> >> Add methods to get a reference to the contained value or populate the
> >> SetOnce if empty. The new `as_ref_or_populate` method accepts a value
> >> directly, while `as_ref_or_populate_with` accepts a fallible closure,
> >> allowing for lazy initialization that may fail. Both methods spin-wait
> >> if another thread is concurrently initializing the container.
> >>
> >> Also add `populate_with` which takes a fallible closure and serves as
> >> the implementation basis for the other populate methods.
> >>
> >> Signed-off-by: Andreas Hindborg <a.hindborg@xxxxxxxxxx>
> >
> >> + /// Get a reference to the contained object, or populate the [`SetOnce`]
> >> + /// with the value returned by `callable` and return a reference to that
> >> + /// object.
> >> + pub fn as_ref_or_populate_with(&self, callable: impl FnOnce() -> Result<T>) -> Result<&T> {
> >> + if !self.populate_with(callable)? {
> >> + while self.init.load(Acquire) != 2 {
> >> + core::hint::spin_loop();
> >> + }
> >
> > We should not be implementing our own spinlocks.
>
> That is a great proverb. I'd be happy to receive a suggestion on an
> alternate approach for this particular context.
You can add a spinlock to SetOnce. Like I mentioned previously [1],
support for waiting will require the addition of extra fields.
I suppose we might be able to use include/linux/bit_spinlock.h here to
avoid taking up any additional space.
Alice
[1]: https://lore.kernel.org/all/CAH5fLggY2Ei14nVJzLBEoR1Rut1GKU4SZX=+14tuRH1aSuQVTA@xxxxxxxxxxxxxx/