Hi!
I come from C++ and C, usually I undersand locking but apparently in rust i ma missing some knowledge?
I am trying to hold a vector of objects in a global variable list so that several threads can work on it in parallel/interleaved manner.
In this case i want a thread to handle all the physics updates.
I don't understand how to create that variable. In C++/C I'd lock the lock manually and all is good, but here the lock is part of the declaration and I am having torouble making a trait be the type of the vector?
use std::{
sync::{LazyLock, Mutex},
thread,
time::Duration,
};
use object::{Object, PhysicsUpdated};
pub mod cube;
pub mod object;
static OBJECT_MANAGER: LazyLock<Mutex<ObjectManager>> =
LazyLock::new(|| Mutex::new(ObjectManager::new()));
struct ObjectManager {
objects: Vec<Box<dyn PhysicsUpdated>>,
physics_thread_handle: thread::JoinHandle<()>,
}
impl ObjectManager {
fn new() -> ObjectManager {
// create a thread that automatically updates the inside objects
let handle = thread::spawn(|| {
{
let mut obj_m = OBJECT_MANAGER.lock().unwrap();
obj_m.objects.iter_mut().for_each(|object| {
object.physics_update(1000.0);
});
}
thread::sleep(Duration::from_secs(1));
});
ObjectManager {
objects: Vec::new(),
physics_thread_handle: handle,
}
}
}
Reading and googling the error message, I know that theere seems to be the issue of my trait not having a fixed size for the object that it implements, fair enough but i was hoping that Box<PhysicsUpdated> could fix that as a 'fat pointer' ?