use std::{
mem::MaybeUninit,
sync::{Mutex, Once},
thread,
time::Duration,
};
struct SingletonReader {
inner: Mutex<u8>,
}
fn singleton() -> &'static SingletonReader {
static mut SINGLETON: MaybeUninit<SingletonReader> = MaybeUninit::uninit();
static ONCE: Once = Once::new();
unsafe {
ONCE.call_once(|| {
let singleton = SingletonReader { inner: Mutex::new(0) };
SINGLETON.write(singleton);
});
SINGLETON.assume_init_ref()
}
}
fn main() {
let threads: Vec<_> = (0..10)
.map(|i| {
thread::spawn(move || {
thread::sleep(Duration::from_millis(i * 10));
let s = singleton();
let mut data = s.inner.lock().unwrap();
*data = i as u8;
})
})
.collect();
for _ in 0u8..20 {
thread::sleep(Duration::from_millis(5));
let s = singleton();
let data = s.inner.lock().unwrap();
println!("It is: {}", *data);
}
for thread in threads.into_iter() {
thread.join().unwrap();
}
}