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)]
75#[expect(clippy::declare_interior_mutable_const, reason = "legacy Once initializer")]
76pub const ONCE_INIT: Once = Once::new();
77
78impl Once {
79 /// Creates a new `Once` value.
80 #[ferrocene::prevalidated]
81 #[inline]
82 #[stable(feature = "once_new", since = "1.2.0")]
83 #[rustc_const_stable(feature = "const_once_new", since = "1.32.0")]
84 #[must_use]
85 pub const fn new() -> Once {
86 #[expect(ferrocene::unvalidated, reason = "defer validating platform specifics")]
87 Once { inner: sys::Once::new() }
88 }
89
90 /// Creates a new `Once` value that starts already completed.
91 #[inline]
92 #[must_use]
93 pub(crate) const fn new_complete() -> Once {
94 Once { inner: sys::Once::new_complete() }
95 }
96
97 /// Performs an initialization routine once and only once. The given closure
98 /// will be executed if this is the first time `call_once` has been called,
99 /// and otherwise the routine will *not* be invoked.
100 ///
101 /// This method will block the calling thread if another initialization
102 /// routine is currently running.
103 ///
104 /// When this function returns, it is guaranteed that some initialization
105 /// has run and completed (it might not be the closure specified). It is also
106 /// guaranteed that any memory writes performed by the executed closure can
107 /// be reliably observed by other threads at this point (there is a
108 /// happens-before relation between the closure and code executing after the
109 /// return).
110 ///
111 /// If the given closure recursively invokes `call_once` on the same [`Once`]
112 /// instance, the exact behavior is not specified: allowed outcomes are
113 /// a panic or a deadlock.
114 ///
115 /// # Examples
116 ///
117 /// ```
118 /// use std::sync::Once;
119 ///
120 /// static mut VAL: usize = 0;
121 /// static INIT: Once = Once::new();
122 ///
123 /// // Accessing a `static mut` is unsafe much of the time, but if we do so
124 /// // in a synchronized fashion (e.g., write once or read all) then we're
125 /// // good to go!
126 /// //
127 /// // This function will only call `expensive_computation` once, and will
128 /// // otherwise always return the value returned from the first invocation.
129 /// fn get_cached_val() -> usize {
130 /// unsafe {
131 /// INIT.call_once(|| {
132 /// VAL = expensive_computation();
133 /// });
134 /// VAL
135 /// }
136 /// }
137 ///
138 /// fn expensive_computation() -> usize {
139 /// // ...
140 /// # 2
141 /// }
142 /// ```
143 ///
144 /// # Panics
145 ///
146 /// The closure `f` will only be executed once even if this is called
147 /// concurrently amongst many threads. If that closure panics, however, then
148 /// it will *poison* this [`Once`] instance, causing all future invocations of
149 /// `call_once` to also panic.
150 ///
151 /// This is similar to [poisoning with mutexes][poison], but this mechanism
152 /// is guaranteed to never skip panics within `f`.
153 ///
154 /// [poison]: struct.Mutex.html#poisoning
155 #[inline]
156 #[stable(feature = "rust1", since = "1.0.0")]
157 #[track_caller]
158 #[lint::should_not_be_called_on_const_items]
159 pub fn call_once<F>(&self, f: F)
160 where
161 F: FnOnce(),
162 {
163 // Fast path check
164 if self.inner.is_completed() {
165 return;
166 }
167
168 let mut f = Some(f);
169 self.inner.call(false, &mut |_| f.take().unwrap()());
170 }
171
172 /// Performs the same function as [`call_once()`] except ignores poisoning.
173 ///
174 /// Unlike [`call_once()`], if this [`Once`] has been poisoned (i.e., a previous
175 /// call to [`call_once()`] or [`call_once_force()`] caused a panic), calling
176 /// [`call_once_force()`] will still invoke the closure `f` and will _not_
177 /// result in an immediate panic. If `f` panics, the [`Once`] will remain
178 /// in a poison state. If `f` does _not_ panic, the [`Once`] will no
179 /// longer be in a poison state and all future calls to [`call_once()`] or
180 /// [`call_once_force()`] will be no-ops.
181 ///
182 /// The closure `f` is yielded a [`OnceState`] structure which can be used
183 /// to query the poison status of the [`Once`].
184 ///
185 /// [`call_once()`]: Once::call_once
186 /// [`call_once_force()`]: Once::call_once_force
187 ///
188 /// # Examples
189 ///
190 /// ```
191 /// use std::sync::Once;
192 /// use std::thread;
193 ///
194 /// static INIT: Once = Once::new();
195 ///
196 /// // poison the once
197 /// let handle = thread::spawn(|| {
198 /// INIT.call_once(|| panic!());
199 /// });
200 /// assert!(handle.join().is_err());
201 ///
202 /// // poisoning propagates
203 /// let handle = thread::spawn(|| {
204 /// INIT.call_once(|| {});
205 /// });
206 /// assert!(handle.join().is_err());
207 ///
208 /// // call_once_force will still run and reset the poisoned state
209 /// INIT.call_once_force(|state| {
210 /// assert!(state.is_poisoned());
211 /// });
212 ///
213 /// // once any success happens, we stop propagating the poison
214 /// INIT.call_once(|| {});
215 /// ```
216 #[inline]
217 #[stable(feature = "once_poison", since = "1.51.0")]
218 #[lint::should_not_be_called_on_const_items]
219 pub fn call_once_force<F>(&self, f: F)
220 where
221 F: FnOnce(&OnceState),
222 {
223 // Fast path check
224 if self.inner.is_completed() {
225 return;
226 }
227
228 let mut f = Some(f);
229 self.inner.call(true, &mut |p| f.take().unwrap()(p));
230 }
231
232 /// Returns `true` if some [`call_once()`] call has completed
233 /// successfully. Specifically, `is_completed` will return false in
234 /// the following situations:
235 /// * [`call_once()`] was not called at all,
236 /// * [`call_once()`] was called, but has not yet completed,
237 /// * the [`Once`] instance is poisoned
238 ///
239 /// This function returning `false` does not mean that [`Once`] has not been
240 /// executed. For example, it may have been executed in the time between
241 /// when `is_completed` starts executing and when it returns, in which case
242 /// the `false` return value would be stale (but still permissible).
243 ///
244 /// [`call_once()`]: Once::call_once
245 ///
246 /// # Examples
247 ///
248 /// ```
249 /// use std::sync::Once;
250 ///
251 /// static INIT: Once = Once::new();
252 ///
253 /// assert_eq!(INIT.is_completed(), false);
254 /// INIT.call_once(|| {
255 /// assert_eq!(INIT.is_completed(), false);
256 /// });
257 /// assert_eq!(INIT.is_completed(), true);
258 /// ```
259 ///
260 /// ```
261 /// use std::sync::Once;
262 /// use std::thread;
263 ///
264 /// static INIT: Once = Once::new();
265 ///
266 /// assert_eq!(INIT.is_completed(), false);
267 /// let handle = thread::spawn(|| {
268 /// INIT.call_once(|| panic!());
269 /// });
270 /// assert!(handle.join().is_err());
271 /// assert_eq!(INIT.is_completed(), false);
272 /// ```
273 #[stable(feature = "once_is_completed", since = "1.43.0")]
274 #[inline]
275 pub fn is_completed(&self) -> bool {
276 self.inner.is_completed()
277 }
278
279 /// Blocks the current thread until initialization has completed.
280 ///
281 /// # Example
282 ///
283 /// ```rust
284 /// use std::sync::Once;
285 /// use std::thread;
286 ///
287 /// static READY: Once = Once::new();
288 ///
289 /// let thread = thread::spawn(|| {
290 /// READY.wait();
291 /// println!("everything is ready");
292 /// });
293 ///
294 /// READY.call_once(|| println!("performing setup"));
295 /// ```
296 ///
297 /// # Panics
298 ///
299 /// If this [`Once`] has been poisoned because an initialization closure has
300 /// panicked, this method will also panic. Use [`wait_force`](Self::wait_force)
301 /// if this behavior is not desired.
302 #[inline]
303 #[stable(feature = "once_wait", since = "1.86.0")]
304 #[lint::should_not_be_called_on_const_items]
305 pub fn wait(&self) {
306 if !self.inner.is_completed() {
307 self.inner.wait(false);
308 }
309 }
310
311 /// Blocks the current thread until initialization has completed, ignoring
312 /// poisoning.
313 ///
314 /// If this [`Once`] has been poisoned, this function blocks until it
315 /// becomes completed, unlike [`Once::wait()`], which panics in this case.
316 #[inline]
317 #[stable(feature = "once_wait", since = "1.86.0")]
318 #[lint::should_not_be_called_on_const_items]
319 pub fn wait_force(&self) {
320 if !self.inner.is_completed() {
321 self.inner.wait(true);
322 }
323 }
324
325 /// Returns the current state of the `Once` instance.
326 ///
327 /// Since this takes a mutable reference, no initialization can currently
328 /// be running, so the state must be either "incomplete", "poisoned" or
329 /// "complete".
330 #[inline]
331 pub(crate) fn state(&mut self) -> OnceExclusiveState {
332 self.inner.state()
333 }
334
335 /// Sets current state of the `Once` instance.
336 ///
337 /// Since this takes a mutable reference, no initialization can currently
338 /// be running, so the state must be either "incomplete", "poisoned" or
339 /// "complete".
340 #[inline]
341 pub(crate) fn set_state(&mut self, new_state: OnceExclusiveState) {
342 self.inner.set_state(new_state);
343 }
344}
345
346#[stable(feature = "std_debug", since = "1.16.0")]
347impl fmt::Debug for Once {
348 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
349 f.debug_struct("Once").finish_non_exhaustive()
350 }
351}
352
353#[stable(feature = "once_default", since = "1.100.0")]
354#[rustc_const_unstable(feature = "const_default", issue = "143894")]
355const impl Default for Once {
356 /// Creates a new `Once` value, same as [`Once::new`].
357 #[inline]
358 fn default() -> Once {
359 Once::new()
360 }
361}
362
363impl OnceState {
364 /// Returns `true` if the associated [`Once`] was poisoned prior to the
365 /// invocation of the closure passed to [`Once::call_once_force()`].
366 ///
367 /// # Examples
368 ///
369 /// A poisoned [`Once`]:
370 ///
371 /// ```
372 /// use std::sync::Once;
373 /// use std::thread;
374 ///
375 /// static INIT: Once = Once::new();
376 ///
377 /// // poison the once
378 /// let handle = thread::spawn(|| {
379 /// INIT.call_once(|| panic!());
380 /// });
381 /// assert!(handle.join().is_err());
382 ///
383 /// INIT.call_once_force(|state| {
384 /// assert!(state.is_poisoned());
385 /// });
386 /// ```
387 ///
388 /// An unpoisoned [`Once`]:
389 ///
390 /// ```
391 /// use std::sync::Once;
392 ///
393 /// static INIT: Once = Once::new();
394 ///
395 /// INIT.call_once_force(|state| {
396 /// assert!(!state.is_poisoned());
397 /// });
398 #[stable(feature = "once_poison", since = "1.51.0")]
399 #[inline]
400 pub fn is_poisoned(&self) -> bool {
401 self.inner.is_poisoned()
402 }
403
404 /// Poison the associated [`Once`] without explicitly panicking.
405 // NOTE: This is currently only exposed for `OnceLock`.
406 #[inline]
407 pub(crate) fn poison(&self) {
408 self.inner.poison();
409 }
410}
411
412#[stable(feature = "std_debug", since = "1.16.0")]
413impl fmt::Debug for OnceState {
414 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
415 f.debug_struct("OnceState").field("poisoned", &self.is_poisoned()).finish()
416 }
417}