pub struct OnceLockFree<T> { /* private fields */ }Expand description
A wait-free alternative to std::sync::OnceLock
This includes a few special purpose helper methods for various use cases. The main advanatge
of these helpers is that they map unexpected states into OnceLockFreeError values.
The helper methods are designed to be used in pairs:
If you need to wait until a value has been registered, use get_poll to read it,
and set to set it.
If you need want to set a value exactly once, wait until everying is set, and then later read the value you have a few options.
If you need to memoize the result, use get_or_prepare_to_set() to check to see if the value
has been set, and then use set_prepared() to install the value. Do this in a way that
guarantees that callers will not race to set the value. After all the sets have completed, you
can use get() or get_or_prepare_to_set() to read values that must be present.
If you want to guarantee that no setters succeed after the first get(), and don’t guarantee that
all values are set by the time initialization completes, use get_or_seal().
Implementations§
Source§impl<'a, T> OnceLockFree<T>
impl<'a, T> OnceLockFree<T>
pub fn get_or_prepare_to_set( &'a self, ) -> Result<Option<&'a T>, OnceLockFreeError>
Sourcepub fn get(&'a self) -> Result<&'a T, OnceLockFreeError>
pub fn get(&'a self) -> Result<&'a T, OnceLockFreeError>
Gets the reference to the underlying value.
Unlike OnceCell and OnceLock, which return an Option<T>, this returns
an Error if the value has not yet been set. There are a few other
variants of get() that are appropriate for other use cases.
Sourcepub fn get_poll(&'a self) -> Option<&'a T>
pub fn get_poll(&'a self) -> Option<&'a T>
Gets the reference to the underlying value, or None if the value has not been set yet.
Sourcepub fn get_or_seal(&'a self) -> Result<Option<&'a T>, OnceLockFreeError>
pub fn get_or_seal(&'a self) -> Result<Option<&'a T>, OnceLockFreeError>
Gets the reference to the underyling value or “seals” self so that it can never be set to a value moving forward.
Returns error if another thread concurrently prepares self, and during shutdown.
Sourcepub fn set_prepared(&'a self, val: T) -> Result<&'a T, OnceLockFreeError>
pub fn set_prepared(&'a self, val: T) -> Result<&'a T, OnceLockFreeError>
set the value after a call to get_or_prepare_to_set returned None. This is done in two phases so that racing sets are more likely to be noticed, and to help callers improve error messages when that happens.
TODO: Add an Error state, and transition into it when racing get_or_prepare_to_set calls occur.
Returns error if already set, or if we haven’t been prepared
Sourcepub fn set(&'a self, val: T) -> Result<&'a T, OnceLockFreeError>
pub fn set(&'a self, val: T) -> Result<&'a T, OnceLockFreeError>
Set this to the provided value. Wait free.
Returns Error if we’ve been prepared, or set already, and a reference to the stored val on success.