std::sync::Once - Rust
Description: API documentation for the Rust `Once` struct in crate `std`.
Keywords: rust, rustlang, rust-lang, Once

# 1.0.0[−][src]Struct std::sync::Once

    pub struct Once { /* fields omitted */ }

A synchronization primitive which can be used to run a one-time global initialization. Useful for one-time initialization for FFI or related functionality. This type can only be constructed with the `ONCE_INIT` value or the equivalent `Once::new` constructor.

# Examples

    use std::sync::Once;

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

    START.call_once(|| {
        // run initialization here
    });Run

## Methods

###

`impl Once`

[src]

####

`pub const fn new() -> Once`

1.2.0
[src]

Creates a new `Once` value.

####

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

[src]

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

    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 {
        // ...
    }Run

# Panics

The closure `f` will only be executed once 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.

####

`pub fn call_once_force<F>(&self, f: F) where F: FnOnce(&OnceState),`

[src]

🔬 This is a nightly-only experimental API. (`once_poison` #33577)

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_one_force` will no-op.

The closure `f` is yielded a `OnceState` structure which can be used to query the poison status of the `Once`.

# Examples

    #![feature(once_poison)]

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

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

####

`pub fn is_completed(&self) -> bool`

[src]

🔬 This is a nightly-only experimental API. (`once_is_completed` #42)

Returns true if some `call_once` call has completed successfuly. Specifically, `is_completed` will return false in the following situtations:

- `call_once` was not called at all,
- `call_once` was called, but has not yet completed,
- the `Once` instance is poisoned

It is also possible that immediately after `is_completed` returns false, some other thread finishes executing `call_once`.

# Examples

    #![feature(once_is_completed)]
    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);Run

    #![feature(once_is_completed)]
    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);Run

## Trait Implementations

###

`impl Debug for Once`

1.16.0
[src]

####

`fn fmt(&self, f: &mut Formatter) -> Result`

[src]

Formats the value using the given formatter. Read more

###

`impl Send for Once`

[src]

###

`impl Sync for Once`

[src]

## Blanket Implementations

###

`impl<T, U> TryFrom for T where T: From<U>,`

[src]

#### `type Error = !`

🔬 This is a nightly-only experimental API. (`try_from` #33417)

The type returned in the event of a conversion error.

####

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

[src]

🔬 This is a nightly-only experimental API. (`try_from` #33417)

Performs the conversion.

###

`impl<T> From for T`

[src]

####

`fn from(t: T) -> T`

[src]

Performs the conversion.

###

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

[src]

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

🔬 This is a nightly-only experimental API. (`try_from` #33417)

The type returned in the event of a conversion error.

####

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

[src]

🔬 This is a nightly-only experimental API. (`try_from` #33417)

Performs the conversion.

###

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

[src]

####

`fn into(self) -> U`

[src]

Performs the conversion.

###

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

[src]

####
ⓘImportant traits for &'a mut I

### Important traits for &'a mut I

`impl<'a, I> Iterator for &'a mut I where
I: Iterator + ?Sized, type Item = <I as Iterator>::Item;impl<'a, R: Read + ?Sized> Read for &'a mut Rimpl<'a, W: Write + ?Sized> Write for &'a mut W`

`fn borrow(&self) -> &T`

[src]

Immutably borrows from an owned value. Read more

###

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

[src]

####
ⓘImportant traits for &'a mut I

### Important traits for &'a mut I

`impl<'a, I> Iterator for &'a mut I where
I: Iterator + ?Sized, type Item = <I as Iterator>::Item;impl<'a, R: Read + ?Sized> Read for &'a mut Rimpl<'a, W: Write + ?Sized> Write for &'a mut W`

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

[src]

Mutably borrows from an owned value. Read more

###

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

[src]

####

`fn get_type_id(&self) -> TypeId`

[src]

🔬 This is a nightly-only experimental API. (`get_type_id` #27745)

this method will likely be replaced by an associated static

Gets the `TypeId` of `self`. Read more

# Help

## Keyboard Shortcuts

`?`
  Show this help dialog
`S`
  Focus the search field
`↑`
  Move up in search results
`↓`
  Move down in search results
`↹`
  Switch tab
`⏎`
  Go to active search result
`+`
  Expand all sections
`-`
  Collapse all sections

## Search Tricks

Prefix searches with a type followed by a colon (e.g. `fn:`) to restrict the search to a given type.

Accepted types are: `fn`, `mod`, `struct`, `enum`, `trait`, `type`, `macro`, and `const`.

Search functions by type signature (e.g. `vec -> usize` or `* -> vec`)

Search multiple things at once by splitting your query with comma (e.g. `str,u8` or `String,struct:Vec,test`)