You can wrap the Vec in a Mutex
Rust
Welcome to the Rust community! This is a place to discuss about the Rust programming language.
Wormhole
Credits
- The icon is a modified version of the official rust logo (changing the colors to a gradient and black background)
OnceLock is the wrong primitive for this. Use a Mutex or an RwLock instead? You can initialize either of them with an empty array at declaration, so you don't need the set_log function. In push_log, do a .lock().unwrap()
for a mutex or .write().unwrap()
for an rwlock to get mutable access to the vector.
Nice, thanks... looking into these now.
Can't you just use the get_or_init
method instead of get
inside the push_log
method? This would initialize the cell on first use. You'd still need a Mutex inside of it to acquire a mutable reference to the vector.
Is the Singleton accessed by one thread or many?
If it's one thread, couldn't you just wrap the Vec
in an Rc
and then clone your singleton every time you need it in a new scope?
If it's many, you should use channels and a dedicated logging thread imo.
One for now, theoretically many later.
Nice I've never used Rc. Maybe now's my chance to look into it.
Look into Arc
, RwLock
, and Mutex
too.
Later, check out parking_lot
and co. and maybe async stuff too.
Async I have a handle on, but I'll take a look at the others for sure.