-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathonce_data.rs
87 lines (78 loc) · 1.97 KB
/
once_data.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
use std::ops::Deref;
use std::sync::atomic::{AtomicPtr, Ordering};
pub struct OnceData<F, T>
where
F: Fn() -> T,
{
f: F,
data: AtomicPtr<T>,
}
impl<F, T> OnceData<F, T>
where
F: Fn() -> T,
{
// `f` is the function that returns data. It's possible that `f` is will be
// called multiple times. But `get` is guaranteed to always return the same
// value.
pub fn new(f: F) -> Self {
Self {
f,
data: AtomicPtr::new(std::ptr::null_mut()),
}
}
fn get(&self) -> &'static T {
let mut p = self.data.load(Ordering::Acquire);
if p.is_null() {
let data = Box::into_raw(Box::new((self.f)()));
p = match self
.data
.compare_exchange_weak(p, data, Ordering::Release, Ordering::Acquire)
{
Ok(_) => {
self.data.store(data, Ordering::Release);
data
}
Err(d) => {
drop(unsafe { Box::from_raw(data) });
d
}
}
}
unsafe { &*p }
}
}
impl<F, T: 'static> Deref for OnceData<F, T>
where
F: Fn() -> T,
{
type Target = T;
fn deref(&self) -> &Self::Target {
self.get()
}
}
pub mod check {
use super::OnceData;
use std::sync::atomic::{AtomicU32, Ordering};
struct Data {
value: u32,
}
fn get_data() -> Data {
static VALUE: AtomicU32 = AtomicU32::new(0);
Data {
value: VALUE.fetch_add(1, Ordering::Relaxed),
}
}
pub fn run() {
let once_data = OnceData::new(get_data);
println!("start: {}", get_data().value);
std::thread::scope(|s| {
for _ in 0..100 {
s.spawn(|| {
let _d = &once_data.value;
println!("{}", _d);
});
}
});
println!("final: {}", get_data().value);
}
}