I'm pretty sure that Arc will be involved somehow... but I just can't wrap my head around the best way to do this.
I want to construct a vector of strings at runtime and stuff (a pointer to?) that vector into a global variable, or, at least, into a variable that will be shared by dynamically created threads. Every once in a while, I will construct a new vector of strings and want to swap out, and discard, the old vector for the new one.
Or, should I use AtomicPtr for this?
As always, tips and pointers are gratefully accepted.
#![feature(once_cell)]
use std::lazy::SyncLazy;
use std::sync::{Arc, RwLock};
const GLOBAL_VEC: SyncLazy<RwLock<Arc<Vec<String>>>> = SyncLazy::new(||
RwLock::new(Arc::new(Vec::new()))
);
fn main() {
{
let lazy = &GLOBAL_VEC;
let lock = SyncLazy::force(lazy);
let mut value = lock.write().unwrap();
*value = Arc::new(vec!["Hello".to_string(), "World".to_string()]);
println!("{value:?}");
}
{
let lazy = &GLOBAL_VEC;
let lock = SyncLazy::force(lazy);
let value = lock.read().unwrap();
println!("{value:?}"); // why does this read `[]`?
}
}
The priority policy of the lock is dependent on the underlying operating system’s implementation, and this type does not guarantee that any particular policy will be used.