Spec-Zone.ru › Tokio

Struct SetOnce

pub struct SetOnce<T> { /* private fields */ }
Available on crate feature sync only.

A thread-safe cell that can be written to only once.

A SetOnce is inspired from python’s asyncio.Event type. It can be used to wait until the value of the SetOnce is set like a “Event” mechanism.

Example

use tokio::sync::{SetOnce, SetOnceError};

static ONCE: SetOnce<u32> = SetOnce::const_new();


// set the value inside a task somewhere...
tokio::spawn(async move { ONCE.set(20) });

// checking with .get doesn't block main thread
println!("{:?}", ONCE.get());

// wait until the value is set, blocks the thread
println!("{:?}", ONCE.wait().await);

Ok(())

A SetOnce is typically used for global variables that need to be initialized once on first use, but need no further changes. The SetOnce in Tokio allows the initialization procedure to be asynchronous.

Example

use tokio::sync::{SetOnce, SetOnceError};
use std::sync::Arc;

let once = SetOnce::new();

let arc = Arc::new(once);
let first_cl = Arc::clone(&arc);
let second_cl = Arc::clone(&arc);

// set the value inside a task
tokio::spawn(async move { first_cl.set(20) }).await.unwrap()?;

// wait inside task to not block the main thread
tokio::spawn(async move {
    // wait inside async context for the value to be set
    assert_eq!(*second_cl.wait().await, 20);
}).await.unwrap();

// subsequent set calls will fail
assert!(arc.set(30).is_err());

println!("{:?}", arc.get());

Ok(())

Implementations

impl<T> SetOnce<T>

pub fn new() -> Self

Creates a new empty SetOnce instance.

pub const fn const_new() -> Self

Creates a new empty SetOnce instance.

Equivalent to SetOnce::new, except that it can be used in static variables.

When using the tracing unstable feature, a SetOnce created with const_new will not be instrumented. As such, it will not be visible in tokio-console. Instead, SetOnce::new should be used to create an instrumented object if that is needed.

Example
use tokio::sync::{SetOnce, SetOnceError};

static ONCE: SetOnce<u32> = SetOnce::const_new();

fn get_global_integer() -> Result<Option<&'static u32>, SetOnceError<u32>> {
    ONCE.set(2)?;
    Ok(ONCE.get())
}

let result = get_global_integer()?;

assert_eq!(result, Some(&2));
Ok(())

pub fn new_with(value: Option<T>) -> Self

Creates a new SetOnce that contains the provided value, if any.

If the Option is None, this is equivalent to SetOnce::new.

pub const fn const_new_with(value: T) -> Self

Creates a new SetOnce that contains the provided value.

Example

When using the tracing unstable feature, a SetOnce created with const_new_with will not be instrumented. As such, it will not be visible in tokio-console. Instead, SetOnce::new_with should be used to create an instrumented object if that is needed.

use tokio::sync::SetOnce;

static ONCE: SetOnce<u32> = SetOnce::const_new_with(1);

fn get_global_integer() -> Option<&'static u32> {
    ONCE.get()
}

let result = get_global_integer();

assert_eq!(result, Some(&1));

pub fn initialized(&self) -> bool

Returns true if the SetOnce currently contains a value, and false otherwise.

pub fn get(&self) -> Option<&T>

Returns a reference to the value currently stored in the SetOnce, or None if the SetOnce is empty.

pub fn set(&self, value: T) -> Result<(), SetOnceError<T>>

Sets the value of the SetOnce to the given value if the SetOnce is empty.

If the SetOnce already has a value, this call will fail with an SetOnceError.

pub fn into_inner(self) -> Option<T>

Takes the value from the cell, destroying the cell in the process. Returns None if the cell is empty.

pub async fn wait(&self) -> &T

Waits until the value is set.

If the SetOnce is already initialized, it will return the value immediately.

Cancel safety

This method is cancel safe.

Trait Implementations

impl<T: Clone> Clone for SetOnce<T>

fn clone(&self) -> SetOnce<T>

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) ·

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more

impl<T: Debug> Debug for SetOnce<T>

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

Formats the value using the given formatter. Read more

impl<T> Default for SetOnce<T>

fn default() -> SetOnce<T>

Returns the “default value” for a type. Read more

impl<T> Drop for SetOnce<T>

fn drop(&mut self)

Executes the destructor for this type. Read more

fn pin_drop(self: Pin<&mut Self>)

🔬This is a nightly-only experimental API. (pin_ergonomics)
Execute the destructor for this type, but different to Drop::drop, it requires self to be pinned. Read more

impl<T: Eq> Eq for SetOnce<T>

impl<T> From<T> for SetOnce<T>

fn from(value: T) -> Self

Converts to this type from the input type.

impl<T: PartialEq> PartialEq for SetOnce<T>

fn eq(&self, other: &SetOnce<T>) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) ·

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more

impl<T: Send> Send for SetOnce<T>

impl<T: Sync + Send> Sync for SetOnce<T>

Auto Trait Implementations

impl<T> !Freeze for SetOnce<T>

impl<T> !RefUnwindSafe for SetOnce<T>

impl<T> Unpin for SetOnce<T>
where T: Unpin,

impl<T> UnsafeUnpin for SetOnce<T>
where T: UnsafeUnpin,

impl<T> UnwindSafe for SetOnce<T>
where T: UnwindSafe,

Blanket Implementations

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

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more

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

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more

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

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

Mutably borrows from an owned value. Read more

impl<T> CloneToUninit for T
where T: Clone,

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more

impl<T> From<!> for T

fn from(t: !) -> T

Converts to this type from the input type.

impl<T> From<T> for T

fn from(t: T) -> T

Returns the argument unchanged.

impl<T> Instrument for T

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

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

fn into(self) -> U

Calls U::from(self).

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

impl<T> ToOwned for T
where T: Clone,

type Owned = T

The resulting type after obtaining ownership.

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more

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

type Error = Infallible

The type returned in the event of a conversion error.

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

Performs the conversion.

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

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

The type returned in the event of a conversion error.

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

Performs the conversion.

impl<T> WithSubscriber for T

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

MIT License
Copyright © Tokio Contributors
https://docs.rs/tokio/1.53.1/tokio/sync/struct.SetOnce.html

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API