Skip to content

Commit aba30a0

Browse files
committed
add OnceCell and OnceLock
1 parent e9619e9 commit aba30a0

File tree

3 files changed

+40
-1
lines changed

3 files changed

+40
-1
lines changed

.DS_Store

10 KB
Binary file not shown.

sync_primitive/src/main.rs

+2
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ fn main() {
1212
rwlock_example();
1313

1414
once_example();
15+
oncecell_example();
16+
oncelock_example();
1517

1618
barrier_example();
1719

sync_primitive/src/once.rs

+38-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,10 @@
22
#![allow(unused_assignments)]
33

44
use std::sync::Once;
5-
5+
use std::sync::OnceLock;
6+
use std::cell::OnceCell;
7+
use std::thread::sleep;
8+
use std::time::Duration;
69

710
pub fn once_example() {
811
let once = Once::new();
@@ -16,4 +19,38 @@ pub fn once_example() {
1619
println!("Once: {}", val);
1720
}
1821

22+
}
23+
24+
pub fn oncecell_example() {
25+
let cell = OnceCell::new();
26+
assert!(cell.get().is_none());
27+
28+
let value: &String = cell.get_or_init(|| {
29+
"Hello, World!".to_string()
30+
});
31+
assert_eq!(value, "Hello, World!");
32+
assert!(cell.get().is_some());
33+
34+
println!("OnceCell: {}", cell.get().is_some())
35+
}
36+
37+
pub fn oncelock_example() {
38+
static CELL: OnceLock<String> = OnceLock::new();
39+
assert!(CELL.get().is_none());
40+
41+
std::thread::spawn(|| {
42+
let value: &String = CELL.get_or_init(|| {
43+
"Hello, World!".to_string()
44+
});
45+
assert_eq!(value, "Hello, World!");
46+
}).join().unwrap();
47+
48+
49+
sleep(Duration::from_secs(1));
50+
51+
let value: Option<&String> = CELL.get();
52+
assert!(value.is_some());
53+
assert_eq!(value.unwrap().as_str(), "Hello, World!");
54+
55+
println!("OnceLock: {}", value.is_some())
1956
}

0 commit comments

Comments
 (0)