pub struct Once { /* private fields */ }
Expand description
A low-level synchronization primitive for one-time global execution.
Previously this was the only “execute once” synchronization in std
.
Other libraries implemented novel synchronizing types with Once
, like
OnceLock<T>
or LazyLock<T, F>
, before those were added to std
.
OnceLock<T>
in particular supersedes Once
in functionality and should
be preferred for the common case where the Once
is associated with data.
This type can only be constructed with Once::new()
.
§Examples
use std::sync::Once;
static START: Once = Once::new();
START.call_once(|| {
// run initialization here
});
Implementations§
source§impl Once
impl Once
1.0.0 · sourcepub fn call_once<F>(&self, f: F)where
F: FnOnce(),
pub fn call_once<F>(&self, f: F)where
F: FnOnce(),
Performs an initialization routine once and only once. The given closure
will be executed if this is the first time call_once
has been called,
and otherwise the routine will not be invoked.
This method will block the calling thread if another initialization routine is currently running.
When this function returns, it is guaranteed that some initialization has run and completed (it might not be the closure specified). It is also guaranteed that any memory writes performed by the executed closure can be reliably observed by other threads at this point (there is a happens-before relation between the closure and code executing after the return).
If the given closure recursively invokes call_once
on the same Once
instance, the exact behavior is not specified: allowed outcomes are
a panic or a deadlock.
§Examples
use std::sync::Once;
static mut VAL: usize = 0;
static INIT: Once = Once::new();
// Accessing a `static mut` is unsafe much of the time, but if we do so
// in a synchronized fashion (e.g., write once or read all) then we're
// good to go!
//
// This function will only call `expensive_computation` once, and will
// otherwise always return the value returned from the first invocation.
fn get_cached_val() -> usize {
unsafe {
INIT.call_once(|| {
VAL = expensive_computation();
});
VAL
}
}
fn expensive_computation() -> usize {
// ...
}
§Panics
The closure f
will only be executed once even if this is called
concurrently amongst many threads. If that closure panics, however, then
it will poison this Once
instance, causing all future invocations of
call_once
to also panic.
This is similar to poisoning with mutexes.
1.51.0 · sourcepub fn call_once_force<F>(&self, f: F)
pub fn call_once_force<F>(&self, f: F)
Performs the same function as call_once()
except ignores poisoning.
Unlike call_once()
, if this Once
has been poisoned (i.e., a previous
call to call_once()
or call_once_force()
caused a panic), calling
call_once_force()
will still invoke the closure f
and will not
result in an immediate panic. If f
panics, the Once
will remain
in a poison state. If f
does not panic, the Once
will no
longer be in a poison state and all future calls to call_once()
or
call_once_force()
will be no-ops.
The closure f
is yielded a OnceState
structure which can be used
to query the poison status of the Once
.
§Examples
use std::sync::Once;
use std::thread;
static INIT: Once = Once::new();
// poison the once
let handle = thread::spawn(|| {
INIT.call_once(|| panic!());
});
assert!(handle.join().is_err());
// poisoning propagates
let handle = thread::spawn(|| {
INIT.call_once(|| {});
});
assert!(handle.join().is_err());
// call_once_force will still run and reset the poisoned state
INIT.call_once_force(|state| {
assert!(state.is_poisoned());
});
// once any success happens, we stop propagating the poison
INIT.call_once(|| {});
1.43.0 · sourcepub fn is_completed(&self) -> bool
pub fn is_completed(&self) -> bool
Returns true
if some call_once()
call has completed
successfully. Specifically, is_completed
will return false in
the following situations:
call_once()
was not called at all,call_once()
was called, but has not yet completed,- the
Once
instance is poisoned
This function returning false
does not mean that Once
has not been
executed. For example, it may have been executed in the time between
when is_completed
starts executing and when it returns, in which case
the false
return value would be stale (but still permissible).
§Examples
use std::sync::Once;
static INIT: Once = Once::new();
assert_eq!(INIT.is_completed(), false);
INIT.call_once(|| {
assert_eq!(INIT.is_completed(), false);
});
assert_eq!(INIT.is_completed(), true);
use std::sync::Once;
use std::thread;
static INIT: Once = Once::new();
assert_eq!(INIT.is_completed(), false);
let handle = thread::spawn(|| {
INIT.call_once(|| panic!());
});
assert!(handle.join().is_err());
assert_eq!(INIT.is_completed(), false);
sourcepub fn wait(&self)
🔬This is a nightly-only experimental API. (once_wait
)
pub fn wait(&self)
once_wait
)Blocks the current thread until initialization has completed.
§Example
#![feature(once_wait)]
use std::sync::Once;
use std::thread;
static READY: Once = Once::new();
let thread = thread::spawn(|| {
READY.wait();
println!("everything is ready");
});
READY.call_once(|| println!("performing setup"));
§Panics
If this Once
has been poisoned because an initialization closure has
panicked, this method will also panic. Use wait_force
if this behaviour is not desired.
sourcepub fn wait_force(&self)
🔬This is a nightly-only experimental API. (once_wait
)
pub fn wait_force(&self)
once_wait
)Blocks the current thread until initialization has completed, ignoring poisoning.
Trait Implementations§
impl RefUnwindSafe for Once
impl UnwindSafe for Once
Auto Trait Implementations§
Blanket Implementations§
source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
source§impl<T> FmtForward for T
impl<T> FmtForward for T
source§fn fmt_binary(self) -> FmtBinary<Self>where
Self: Binary,
fn fmt_binary(self) -> FmtBinary<Self>where
Self: Binary,
self
to use its Binary
implementation when Debug
-formatted.source§fn fmt_display(self) -> FmtDisplay<Self>where
Self: Display,
fn fmt_display(self) -> FmtDisplay<Self>where
Self: Display,
self
to use its Display
implementation when
Debug
-formatted.source§fn fmt_lower_exp(self) -> FmtLowerExp<Self>where
Self: LowerExp,
fn fmt_lower_exp(self) -> FmtLowerExp<Self>where
Self: LowerExp,
self
to use its LowerExp
implementation when
Debug
-formatted.source§fn fmt_lower_hex(self) -> FmtLowerHex<Self>where
Self: LowerHex,
fn fmt_lower_hex(self) -> FmtLowerHex<Self>where
Self: LowerHex,
self
to use its LowerHex
implementation when
Debug
-formatted.source§fn fmt_octal(self) -> FmtOctal<Self>where
Self: Octal,
fn fmt_octal(self) -> FmtOctal<Self>where
Self: Octal,
self
to use its Octal
implementation when Debug
-formatted.source§fn fmt_pointer(self) -> FmtPointer<Self>where
Self: Pointer,
fn fmt_pointer(self) -> FmtPointer<Self>where
Self: Pointer,
self
to use its Pointer
implementation when
Debug
-formatted.source§fn fmt_upper_exp(self) -> FmtUpperExp<Self>where
Self: UpperExp,
fn fmt_upper_exp(self) -> FmtUpperExp<Self>where
Self: UpperExp,
self
to use its UpperExp
implementation when
Debug
-formatted.source§fn fmt_upper_hex(self) -> FmtUpperHex<Self>where
Self: UpperHex,
fn fmt_upper_hex(self) -> FmtUpperHex<Self>where
Self: UpperHex,
self
to use its UpperHex
implementation when
Debug
-formatted.source§impl<T> IntoEither for T
impl<T> IntoEither for T
source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
self
into a Left
variant of Either<Self, Self>
if into_left
is true
.
Converts self
into a Right
variant of Either<Self, Self>
otherwise. Read moresource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
self
into a Left
variant of Either<Self, Self>
if into_left(&self)
returns true
.
Converts self
into a Right
variant of Either<Self, Self>
otherwise. Read moresource§impl<T> Pipe for Twhere
T: ?Sized,
impl<T> Pipe for Twhere
T: ?Sized,
source§fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> Rwhere
Self: Sized,
fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> Rwhere
Self: Sized,
source§fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> Rwhere
R: 'a,
fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> Rwhere
R: 'a,
self
and passes that borrow into the pipe function. Read moresource§fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> Rwhere
R: 'a,
fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> Rwhere
R: 'a,
self
and passes that borrow into the pipe function. Read moresource§fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> R
fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> R
source§fn pipe_borrow_mut<'a, B, R>(
&'a mut self,
func: impl FnOnce(&'a mut B) -> R,
) -> R
fn pipe_borrow_mut<'a, B, R>( &'a mut self, func: impl FnOnce(&'a mut B) -> R, ) -> R
source§fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> R
fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> R
self
, then passes self.as_ref()
into the pipe function.source§fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mut U) -> R) -> R
fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mut U) -> R) -> R
self
, then passes self.as_mut()
into the pipe
function.source§fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'a T) -> R) -> R
fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'a T) -> R) -> R
self
, then passes self.deref()
into the pipe function.source§impl<T> Tap for T
impl<T> Tap for T
source§fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self
fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self
Borrow<B>
of a value. Read moresource§fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Self
fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Self
BorrowMut<B>
of a value. Read moresource§fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self
fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self
AsRef<R>
view of a value. Read moresource§fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Self
fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Self
AsMut<R>
view of a value. Read moresource§fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self
fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self
Deref::Target
of a value. Read moresource§fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Self
fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Self
Deref::Target
of a value. Read moresource§fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self
fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self
.tap()
only in debug builds, and is erased in release builds.source§fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self
fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self
.tap_mut()
only in debug builds, and is erased in release
builds.source§fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self
fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self
.tap_borrow()
only in debug builds, and is erased in release
builds.source§fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mut B)) -> Self
fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mut B)) -> Self
.tap_borrow_mut()
only in debug builds, and is erased in release
builds.source§fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self
fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self
.tap_ref()
only in debug builds, and is erased in release
builds.source§fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mut R)) -> Self
fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mut R)) -> Self
.tap_ref_mut()
only in debug builds, and is erased in release
builds.source§fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self
fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self
.tap_deref()
only in debug builds, and is erased in release
builds.