Once

Struct Once 

Source
pub struct Once { /* private fields */ }
Expand description

A synchronization primitive which can be used to run a one-time global initialization.

Once behaves like std::sync::Once except for using spinlock. Useful for one-time initialization for FFI or related functionality.

§Examples

use spin_sync::Once;

static INIT: Once = Once::new();

INIT.call_once(|| {
    // Do some initialization here.
});

Implementations§

Source§

impl Once

Source

pub const fn new() -> Self

Create a new Once instance.

Source

pub fn call_once<F: FnOnce()>(&self, f: F)

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 may 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

Once enable to access static mut data safely.

use spin_sync::Once;

static mut CACHE: usize = 0;
static INIT: Once = Once::new();

fn expensive_calculation(val: usize) -> usize {
    unsafe {
        INIT.call_once(|| { CACHE = val; });
        CACHE
    }
}

// INIT.call_once() invokes the closure and set the CACHE.
assert_eq!(1, expensive_calculation(1));

// INIT.call_once() do nothing and return the CACHE.
assert_eq!(1, expensive_calculation(2));
§Panics

The closure f will only be executed once if this is called concurrently among many threads. If that closure panics, however, then it will poison this Once instance, causing all future invocations of call_once to also panic.

Source

pub fn call_once_force<F: FnOnce(&OnceState)>(&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 spin_sync::Once;
use std::thread;

static INIT: Once = Once::new();

// Poison INIT
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.poisoned());
});

// once any success happens, we stop propagating the poison
INIT.call_once(|| {});
Source

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:

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

call_once was succeeded.

use spin_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);

call_once caused panic.

use spin_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);

Trait Implementations§

Source§

impl Debug for Once

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl !Freeze for Once

§

impl RefUnwindSafe for Once

§

impl Send for Once

§

impl Sync for Once

§

impl Unpin for Once

§

impl UnwindSafe for Once

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.