pub struct SetOnce<T> { /* private fields */ }
Expand description
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();
#[tokio::main]
async fn main() -> Result<(), SetOnceError<u32>> {
// 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;
#[tokio::main]
async fn main() -> Result<(), SetOnceError<u32>> {
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§
Source§impl<T> SetOnce<T>
impl<T> SetOnce<T>
Sourcepub const fn const_new() -> Self
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())
}
#[tokio::main]
async fn main() -> Result<(), SetOnceError<u32>> {
let result = get_global_integer()?;
assert_eq!(result, Some(&2));
Ok(())
}
Sourcepub fn new_with(value: Option<T>) -> Self
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
.
Sourcepub const fn const_new_with(value: T) -> Self
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()
}
#[tokio::main]
async fn main() {
let result = get_global_integer();
assert_eq!(result, Some(&1));
}
Sourcepub fn initialized(&self) -> bool
pub fn initialized(&self) -> bool
Returns true
if the SetOnce
currently contains a value, and false
otherwise.
Sourcepub fn get(&self) -> Option<&T>
pub fn get(&self) -> Option<&T>
Returns a reference to the value currently stored in the SetOnce
, or
None
if the SetOnce
is empty.
Sourcepub fn set(&self, value: T) -> Result<(), SetOnceError<T>>
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
.
Sourcepub fn into_inner(self) -> Option<T>
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.
Sourcepub async fn wait(&self) -> &T
pub async fn wait(&self) -> &T
Waits until set is called. The future returned will keep blocking until
the SetOnce
is initialized.
If the SetOnce
is already initialized, it will return the value
immediately.
§Note
This will keep waiting until the SetOnce
is initialized, so it
should be used with care to avoid blocking the current task
indefinitely.