Re: [PATCH v4 1/3] rust: Add `OnceLite` for executing code once

From: Alice Ryhl
Date: Wed Nov 27 2024 - 15:18:23 EST


On Wed, Nov 27, 2024 at 9:12 PM <jens.korinth@xxxxxxx> wrote:
>
> > What is the use-case for this function?
>
> `DO_ONCE_LITE` has very few uses in C; frankly, the only other use I could think
> of was initialization. But since `OnceLite` cannot block or guarantee visibility
> of the side-effects of the `call_once` expression in other threads, it can't be
> used for this case, either. _Unless_ there is some mechanism to wait
> voluntarily when this is required, hence `is_completed`. (And it also exists in
> `std::sync::Once`.)
>
> `DO_ONCE_LITE_IF` has more uses in C, but this is a bit harder to do well with
> `OnceLite`: A `do_once_lite_if` Rust macro can't short-circuit the condition to
> avoid the evaluation if the atomic load already shows that it has been done / is
> being done rn. Maybe a
> `pub fn call_once<C: FnOnce() -> bool, F: FnOnce()>(cond: C, f: F)` could be
> used to simulate the effect. Thoughts?
>
> > Why not just have one atomic?
>
> Do you also have an `AtomicU32` state var in mind, as Daniel suggested?

What I had in mind was to use a single AtomicBool and get rid of the
`is_completed` logic entirely. The purpose is to use this for printing
once, and printing doesn't need `is_completed`. We can have another
helper for other purposes.

Alice