std/sync/once.rs
1//! A "once initialization" primitive
2//!
3//! This primitive is meant to be used to run one-time initialization. An
4//! example use case would be for initializing an FFI library.
5
6use crate::fmt;
7use crate::panic::{RefUnwindSafe, UnwindSafe};
8use crate::sys::sync as sys;
9
10/// A low-level synchronization primitive for one-time global execution.
11///
12/// Previously this was the only "execute once" synchronization in `std`.
13/// Other libraries implemented novel synchronizing types with `Once`, like
14/// [`OnceLock<T>`] or [`LazyLock<T, F>`], before those were added to `std`.
15/// `OnceLock<T>` in particular supersedes `Once` in functionality and should
16/// be preferred for the common case where the `Once` is associated with data.
17///
18/// This type can only be constructed with [`Once::new()`].
19///
20/// # Examples
21///
22/// ```
23/// use std::sync::Once;
24///
25/// static START: Once = Once::new();
26///
27/// START.call_once(|| {
28/// // run initialization here
29/// });
30/// ```
31///
32/// [`OnceLock<T>`]: crate::sync::OnceLock
33/// [`LazyLock<T, F>`]: crate::sync::LazyLock
34#[stable(feature = "rust1", since = "1.0.0")]
35pub struct Once {
36 inner: sys::Once,
37}
38
39#[stable(feature = "sync_once_unwind_safe", since = "1.59.0")]
40impl UnwindSafe for Once {}
41
42#[stable(feature = "sync_once_unwind_safe", since = "1.59.0")]
43impl RefUnwindSafe for Once {}
44
45/// State yielded to [`Once::call_once_force()`]’s closure parameter. The state
46/// can be used to query the poison status of the [`Once`].
47#[stable(feature = "once_poison", since = "1.51.0")]
48pub struct OnceState {
49 pub(crate) inner: sys::OnceState,
50}
51
52/// Used for the internal implementation of `sys::sync::once` on different platforms and the
53/// [`LazyLock`](crate::sync::LazyLock) implementation.
54pub(crate) enum OnceExclusiveState {
55 Incomplete,
56 Poisoned,
57 Complete,
58}
59
60/// Initialization value for static [`Once`] values.
61///
62/// # Examples
63///
64/// ```
65/// use std::sync::{Once, ONCE_INIT};
66///
67/// static START: Once = ONCE_INIT;
68/// ```
69#[stable(feature = "rust1", since = "1.0.0")]
70#[deprecated(
71 since = "1.38.0",
72 note = "the `Once::new()` function is now preferred",
73 suggestion = "Once::new()"
74)]
75pub const ONCE_INIT: Once = Once::new();
76
77impl Once {
78 /// Creates a new `Once` value.
79 #[inline]
80 #[stable(feature = "once_new", since = "1.2.0")]
81 #[rustc_const_stable(feature = "const_once_new", since = "1.32.0")]
82 #[must_use]
83 pub const fn new() -> Once {
84 Once { inner: sys::Once::new() }
85 }
86
87 /// Performs an initialization routine once and only once. The given closure
88 /// will be executed if this is the first time `call_once` has been called,
89 /// and otherwise the routine will *not* be invoked.
90 ///
91 /// This method will block the calling thread if another initialization
92 /// routine is currently running.
93 ///
94 /// When this function returns, it is guaranteed that some initialization
95 /// has run and completed (it might not be the closure specified). It is also
96 /// guaranteed that any memory writes performed by the executed closure can
97 /// be reliably observed by other threads at this point (there is a
98 /// happens-before relation between the closure and code executing after the
99 /// return).
100 ///
101 /// If the given closure recursively invokes `call_once` on the same [`Once`]
102 /// instance, the exact behavior is not specified: allowed outcomes are
103 /// a panic or a deadlock.
104 ///
105 /// # Examples
106 ///
107 /// ```
108 /// use std::sync::Once;
109 ///
110 /// static mut VAL: usize = 0;
111 /// static INIT: Once = Once::new();
112 ///
113 /// // Accessing a `static mut` is unsafe much of the time, but if we do so
114 /// // in a synchronized fashion (e.g., write once or read all) then we're
115 /// // good to go!
116 /// //
117 /// // This function will only call `expensive_computation` once, and will
118 /// // otherwise always return the value returned from the first invocation.
119 /// fn get_cached_val() -> usize {
120 /// unsafe {
121 /// INIT.call_once(|| {
122 /// VAL = expensive_computation();
123 /// });
124 /// VAL
125 /// }
126 /// }
127 ///
128 /// fn expensive_computation() -> usize {
129 /// // ...
130 /// # 2
131 /// }
132 /// ```
133 ///
134 /// # Panics
135 ///
136 /// The closure `f` will only be executed once even if this is called
137 /// concurrently amongst many threads. If that closure panics, however, then
138 /// it will *poison* this [`Once`] instance, causing all future invocations of
139 /// `call_once` to also panic.
140 ///
141 /// This is similar to [poisoning with mutexes][poison], but this mechanism
142 /// is guaranteed to never skip panics within `f`.
143 ///
144 /// [poison]: struct.Mutex.html#poisoning
145 #[inline]
146 #[stable(feature = "rust1", since = "1.0.0")]
147 #[track_caller]
148 pub fn call_once<F>(&self, f: F)
149 where
150 F: FnOnce(),
151 {
152 // Fast path check
153 if self.inner.is_completed() {
154 return;
155 }
156
157 let mut f = Some(f);
158 self.inner.call(false, &mut |_| f.take().unwrap()());
159 }
160
161 /// Performs the same function as [`call_once()`] except ignores poisoning.
162 ///
163 /// Unlike [`call_once()`], if this [`Once`] has been poisoned (i.e., a previous
164 /// call to [`call_once()`] or [`call_once_force()`] caused a panic), calling
165 /// [`call_once_force()`] will still invoke the closure `f` and will _not_
166 /// result in an immediate panic. If `f` panics, the [`Once`] will remain
167 /// in a poison state. If `f` does _not_ panic, the [`Once`] will no
168 /// longer be in a poison state and all future calls to [`call_once()`] or
169 /// [`call_once_force()`] will be no-ops.
170 ///
171 /// The closure `f` is yielded a [`OnceState`] structure which can be used
172 /// to query the poison status of the [`Once`].
173 ///
174 /// [`call_once()`]: Once::call_once
175 /// [`call_once_force()`]: Once::call_once_force
176 ///
177 /// # Examples
178 ///
179 /// ```
180 /// use std::sync::Once;
181 /// use std::thread;
182 ///
183 /// static INIT: Once = Once::new();
184 ///
185 /// // poison the once
186 /// let handle = thread::spawn(|| {
187 /// INIT.call_once(|| panic!());
188 /// });
189 /// assert!(handle.join().is_err());
190 ///
191 /// // poisoning propagates
192 /// let handle = thread::spawn(|| {
193 /// INIT.call_once(|| {});
194 /// });
195 /// assert!(handle.join().is_err());
196 ///
197 /// // call_once_force will still run and reset the poisoned state
198 /// INIT.call_once_force(|state| {
199 /// assert!(state.is_poisoned());
200 /// });
201 ///
202 /// // once any success happens, we stop propagating the poison
203 /// INIT.call_once(|| {});
204 /// ```
205 #[inline]
206 #[stable(feature = "once_poison", since = "1.51.0")]
207 pub fn call_once_force<F>(&self, f: F)
208 where
209 F: FnOnce(&OnceState),
210 {
211 // Fast path check
212 if self.inner.is_completed() {
213 return;
214 }
215
216 let mut f = Some(f);
217 self.inner.call(true, &mut |p| f.take().unwrap()(p));
218 }
219
220 /// Returns `true` if some [`call_once()`] call has completed
221 /// successfully. Specifically, `is_completed` will return false in
222 /// the following situations:
223 /// * [`call_once()`] was not called at all,
224 /// * [`call_once()`] was called, but has not yet completed,
225 /// * the [`Once`] instance is poisoned
226 ///
227 /// This function returning `false` does not mean that [`Once`] has not been
228 /// executed. For example, it may have been executed in the time between
229 /// when `is_completed` starts executing and when it returns, in which case
230 /// the `false` return value would be stale (but still permissible).
231 ///
232 /// [`call_once()`]: Once::call_once
233 ///
234 /// # Examples
235 ///
236 /// ```
237 /// use std::sync::Once;
238 ///
239 /// static INIT: Once = Once::new();
240 ///
241 /// assert_eq!(INIT.is_completed(), false);
242 /// INIT.call_once(|| {
243 /// assert_eq!(INIT.is_completed(), false);
244 /// });
245 /// assert_eq!(INIT.is_completed(), true);
246 /// ```
247 ///
248 /// ```
249 /// use std::sync::Once;
250 /// use std::thread;
251 ///
252 /// static INIT: Once = Once::new();
253 ///
254 /// assert_eq!(INIT.is_completed(), false);
255 /// let handle = thread::spawn(|| {
256 /// INIT.call_once(|| panic!());
257 /// });
258 /// assert!(handle.join().is_err());
259 /// assert_eq!(INIT.is_completed(), false);
260 /// ```
261 #[stable(feature = "once_is_completed", since = "1.43.0")]
262 #[inline]
263 pub fn is_completed(&self) -> bool {
264 self.inner.is_completed()
265 }
266
267 /// Blocks the current thread until initialization has completed.
268 ///
269 /// # Example
270 ///
271 /// ```rust
272 /// use std::sync::Once;
273 /// use std::thread;
274 ///
275 /// static READY: Once = Once::new();
276 ///
277 /// let thread = thread::spawn(|| {
278 /// READY.wait();
279 /// println!("everything is ready");
280 /// });
281 ///
282 /// READY.call_once(|| println!("performing setup"));
283 /// ```
284 ///
285 /// # Panics
286 ///
287 /// If this [`Once`] has been poisoned because an initialization closure has
288 /// panicked, this method will also panic. Use [`wait_force`](Self::wait_force)
289 /// if this behavior is not desired.
290 #[stable(feature = "once_wait", since = "1.86.0")]
291 pub fn wait(&self) {
292 if !self.inner.is_completed() {
293 self.inner.wait(false);
294 }
295 }
296
297 /// Blocks the current thread until initialization has completed, ignoring
298 /// poisoning.
299 ///
300 /// If this [`Once`] has been poisoned, this function blocks until it
301 /// becomes completed, unlike [`Once::wait()`], which panics in this case.
302 #[stable(feature = "once_wait", since = "1.86.0")]
303 pub fn wait_force(&self) {
304 if !self.inner.is_completed() {
305 self.inner.wait(true);
306 }
307 }
308
309 /// Returns the current state of the `Once` instance.
310 ///
311 /// Since this takes a mutable reference, no initialization can currently
312 /// be running, so the state must be either "incomplete", "poisoned" or
313 /// "complete".
314 #[inline]
315 pub(crate) fn state(&mut self) -> OnceExclusiveState {
316 self.inner.state()
317 }
318
319 /// Sets current state of the `Once` instance.
320 ///
321 /// Since this takes a mutable reference, no initialization can currently
322 /// be running, so the state must be either "incomplete", "poisoned" or
323 /// "complete".
324 #[inline]
325 pub(crate) fn set_state(&mut self, new_state: OnceExclusiveState) {
326 self.inner.set_state(new_state);
327 }
328}
329
330#[stable(feature = "std_debug", since = "1.16.0")]
331impl fmt::Debug for Once {
332 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
333 f.debug_struct("Once").finish_non_exhaustive()
334 }
335}
336
337impl OnceState {
338 /// Returns `true` if the associated [`Once`] was poisoned prior to the
339 /// invocation of the closure passed to [`Once::call_once_force()`].
340 ///
341 /// # Examples
342 ///
343 /// A poisoned [`Once`]:
344 ///
345 /// ```
346 /// use std::sync::Once;
347 /// use std::thread;
348 ///
349 /// static INIT: Once = Once::new();
350 ///
351 /// // poison the once
352 /// let handle = thread::spawn(|| {
353 /// INIT.call_once(|| panic!());
354 /// });
355 /// assert!(handle.join().is_err());
356 ///
357 /// INIT.call_once_force(|state| {
358 /// assert!(state.is_poisoned());
359 /// });
360 /// ```
361 ///
362 /// An unpoisoned [`Once`]:
363 ///
364 /// ```
365 /// use std::sync::Once;
366 ///
367 /// static INIT: Once = Once::new();
368 ///
369 /// INIT.call_once_force(|state| {
370 /// assert!(!state.is_poisoned());
371 /// });
372 #[stable(feature = "once_poison", since = "1.51.0")]
373 #[inline]
374 pub fn is_poisoned(&self) -> bool {
375 self.inner.is_poisoned()
376 }
377
378 /// Poison the associated [`Once`] without explicitly panicking.
379 // NOTE: This is currently only exposed for `OnceLock`.
380 #[inline]
381 pub(crate) fn poison(&self) {
382 self.inner.poison();
383 }
384}
385
386#[stable(feature = "std_debug", since = "1.16.0")]
387impl fmt::Debug for OnceState {
388 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
389 f.debug_struct("OnceState").field("poisoned", &self.is_poisoned()).finish()
390 }
391}