Struct std::lazy::SyncOnceCell [−][src]
pub struct SyncOnceCell<T> { /* fields omitted */ }
Expand description
只能写入一次的同步原语。
此类型是线程安全的 OnceCell
。
Examples
#![feature(once_cell)]
use std::lazy::SyncOnceCell;
static CELL: SyncOnceCell<String> = SyncOnceCell::new();
assert!(CELL.get().is_none());
std::thread::spawn(|| {
let value: &String = CELL.get_or_init(|| {
"Hello, World!".to_string()
});
assert_eq!(value, "Hello, World!");
}).join().unwrap();
let value: Option<&String> = CELL.get();
assert!(value.is_some());
assert_eq!(value.unwrap().as_str(), "Hello, World!");
RunImplementations
创建一个新的空 cell。
获取对底层值的引用。
如果 cell 为空或正在初始化,则返回 None
。
此方法永远不会阻塞。
获取对底层值的可变引用。
如果 cell 为空,则返回 None
。此方法永远不会阻塞。
将此 cell 的内容设置为 value
。
如果另一个线程当前正在尝试初始化该 cell,则可能会阻塞。 尽管 set 不一定返回,但保证该 cell 包含一个值。
如果此调用设置了 cell 的值,则返回 Ok(())
。
Examples
#![feature(once_cell)]
use std::lazy::SyncOnceCell;
static CELL: SyncOnceCell<i32> = SyncOnceCell::new();
fn main() {
assert!(CELL.get().is_none());
std::thread::spawn(|| {
assert_eq!(CELL.set(92), Ok(()));
}).join().unwrap();
assert_eq!(CELL.set(62), Err(62));
assert_eq!(CELL.get(), Some(&92));
}
Run获取 cell 的内容,如果 cell 为空,则使用 f
对其进行初始化。
许多线程可以使用不同的初始化函数并发调用 get_or_init
,但是可以保证仅执行一个函数。
Panics
如果 f
panics,则 panic 会传播给调用者,并且 cell 仍保持未初始化状态。
重新从 f
初始化 cell 是错误的。确切的结果是不确定的。
当前的实现死锁,但是可以在 future 中将其更改为 panic。
Examples
#![feature(once_cell)]
use std::lazy::SyncOnceCell;
let cell = SyncOnceCell::new();
let value = cell.get_or_init(|| 92);
assert_eq!(value, &92);
let value = cell.get_or_init(|| unreachable!());
assert_eq!(value, &92);
Run获取 cell 的内容,如果 cell 为空,则使用 f
对其进行初始化。
如果 cell 为空并且 f
失败,则返回错误。
Panics
如果 f
panics,则 panic 会传播给调用者,并且 cell 仍保持未初始化状态。
重新从 f
初始化 cell 是错误的。
确切的结果是不确定的。
当前的实现死锁,但是可以在 future 中将其更改为 panic。
Examples
#![feature(once_cell)]
use std::lazy::SyncOnceCell;
let cell = SyncOnceCell::new();
assert_eq!(cell.get_or_try_init(|| Err(())), Err(()));
assert!(cell.get().is_none());
let value = cell.get_or_try_init(|| -> Result<i32, ()> {
Ok(92)
});
assert_eq!(value, Ok(&92));
assert_eq!(cell.get(), Some(&92))
Run消耗 SyncOnceCell
,返回包装的值。
如果 cell 为空,则返回 None
。
Examples
#![feature(once_cell)]
use std::lazy::SyncOnceCell;
let cell: SyncOnceCell<String> = SyncOnceCell::new();
assert_eq!(cell.into_inner(), None);
let cell = SyncOnceCell::new();
cell.set("hello".to_string()).unwrap();
assert_eq!(cell.into_inner(), Some("hello".to_string()));
Run从 SyncOnceCell
中取出值,将其移回未初始化状态。
无效,如果尚未初始化 SyncOnceCell
,则返回 None
。
通过要求可变引用来保证安全。
Examples
#![feature(once_cell)]
use std::lazy::SyncOnceCell;
let mut cell: SyncOnceCell<String> = SyncOnceCell::new();
assert_eq!(cell.take(), None);
let mut cell = SyncOnceCell::new();
cell.set("hello".to_string()).unwrap();
assert_eq!(cell.take(), Some("hello".to_string()));
assert_eq!(cell.get(), None);
Run