pub struct Once { /* private fields */ }
sync_poison_mod
)std
only.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 behavior 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ยง
Sourceยงimpl ConstDefault for Once
impl ConstDefault for Once
ยงimpl OnceExt for Once
impl OnceExt for Once
ยงfn call_once_py_attached(&self, py: Python<'_>, f: impl FnOnce())
fn call_once_py_attached(&self, py: Python<'_>, f: impl FnOnce())
call_once
, but releases the Python GIL temporarily
if blocking on another thread currently calling this Once
.ยงfn call_once_force_py_attached(
&self,
py: Python<'_>,
f: impl FnOnce(&OnceState),
)
fn call_once_force_py_attached( &self, py: Python<'_>, f: impl FnOnce(&OnceState), )
call_once_force
, but releases the Python GIL
temporarily if blocking on another thread currently calling this Once
.impl RefUnwindSafe for Once
impl UnwindSafe for Once
Auto Trait Implementationsยง
Blanket Implementationsยง
ยงimpl<T> ArchivePointee for T
impl<T> ArchivePointee for T
ยงtype ArchivedMetadata = ()
type ArchivedMetadata = ()
ยงfn pointer_metadata(
_: &<T as ArchivePointee>::ArchivedMetadata,
) -> <T as Pointee>::Metadata
fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata, ) -> <T as Pointee>::Metadata
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> ByteSized for T
impl<T> ByteSized for T
Sourceยงconst BYTE_ALIGN: usize = _
const BYTE_ALIGN: usize = _
Sourceยงfn byte_align(&self) -> usize โ
fn byte_align(&self) -> usize โ
Sourceยงfn ptr_size_ratio(&self) -> [usize; 2]
fn ptr_size_ratio(&self) -> [usize; 2]
Sourceยงimpl<T, R> Chain<R> for Twhere
T: ?Sized,
impl<T, R> Chain<R> for Twhere
T: ?Sized,
Sourceยงimpl<T> ExtAny for T
impl<T> ExtAny for T
Sourceยงfn as_any_mut(&mut self) -> &mut dyn Anywhere
Self: Sized,
fn as_any_mut(&mut self) -> &mut dyn Anywhere
Self: Sized,
Sourceยงimpl<T> ExtMem for Twhere
T: ?Sized,
impl<T> ExtMem for Twhere
T: ?Sized,
Sourceยงconst NEEDS_DROP: bool = _
const NEEDS_DROP: bool = _
Sourceยงfn mem_align_of<T>() -> usize โ
fn mem_align_of<T>() -> usize โ
Sourceยงfn mem_align_of_val(&self) -> usize โ
fn mem_align_of_val(&self) -> usize โ
Sourceยงfn mem_size_of_val(&self) -> usize โ
fn mem_size_of_val(&self) -> usize โ
Sourceยงfn mem_needs_drop(&self) -> bool
fn mem_needs_drop(&self) -> bool
true
if dropping values of this type matters. Read moreSourceยงfn mem_forget(self)where
Self: Sized,
fn mem_forget(self)where
Self: Sized,
self
without running its destructor. Read moreSourceยงfn mem_replace(&mut self, other: Self) -> Selfwhere
Self: Sized,
fn mem_replace(&mut self, other: Self) -> Selfwhere
Self: Sized,
Sourceยงunsafe fn mem_zeroed<T>() -> T
unsafe fn mem_zeroed<T>() -> T
unsafe_layout
only.T
represented by the all-zero byte-pattern. Read moreSourceยงunsafe fn mem_transmute_copy<Src, Dst>(src: &Src) -> Dst
unsafe fn mem_transmute_copy<Src, Dst>(src: &Src) -> Dst
unsafe_layout
only.T
represented by the all-zero byte-pattern. Read moreSourceยงfn mem_as_bytes(&self) -> &[u8] โ
fn mem_as_bytes(&self) -> &[u8] โ
unsafe_slice
only.ยงimpl<S> FromSample<S> for S
impl<S> FromSample<S> for S
fn from_sample_(s: S) -> S
Sourceยงimpl<T> Hook for T
impl<T> Hook for T
ยงimpl<T> Instrument for T
impl<T> Instrument for T
ยงfn instrument(self, span: Span) -> Instrumented<Self> โ
fn instrument(self, span: Span) -> Instrumented<Self> โ
ยงfn in_current_span(self) -> Instrumented<Self> โ
fn in_current_span(self) -> Instrumented<Self> โ
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 moreยงimpl<F, T> IntoSample<T> for Fwhere
T: FromSample<F>,
impl<F, T> IntoSample<T> for Fwhere
T: FromSample<F>,
fn into_sample(self) -> T
ยงimpl<T> LayoutRaw for T
impl<T> LayoutRaw for T
ยงfn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutError> โ
fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutError> โ
ยงimpl<T, N1, N2> Niching<NichedOption<T, N1>> for N2
impl<T, N1, N2> Niching<NichedOption<T, N1>> for N2
ยงunsafe fn is_niched(niched: *const NichedOption<T, N1>) -> bool
unsafe fn is_niched(niched: *const NichedOption<T, N1>) -> bool
ยงfn resolve_niched(out: Place<NichedOption<T, N1>>)
fn resolve_niched(out: Place<NichedOption<T, N1>>)
out
indicating that a T
is niched.