I'm quite new to rust and want to do two function in parallel.
shoot(&fleet_a, &mut fleet_b)
shoot(&fleet_b, &mut fleet_a)
since they only take information from one and modify some values of the other one this should be save to do. However it always complains that i am using them after moving, can I somehow tell the rust compiler that it is save to do so?
Here an example code:
use std::sync::Arc;
use std::thread;
pub struct Ship {
pub hull: f32,
pub shield: f32,
pub info: Arc<ShipInfo>,
}
#[derive(Clone)]
pub struct ShipInfo {
pub attack: f32,
pub ship_id: usize,
}
fn shoot(attacker:&[Ship],defender:&mut [Ship]){
//do some calculations here, reading the info of the attacker and changing values of the defender
}
fn main(){
let sinfo=Arc::new( ShipInfo{
attack:10.0,
ship_id:1,
});
let mut ships_a:Vec<Ship>=Vec::new();
let mut ships_b:Vec<Ship>=Vec::new();
for _ in 0..100{
ships_a.push(Ship{
hull:42.0,
shield:44.0,
info:sinfo.clone(),
});
}
for _ in 0..1000{
ships_b.push(Ship{
hull:44.0,
shield:23.0,
info:sinfo.clone(),
});
}
shoot(&ships_a, &mut ships_b);
shoot(&ships_b, &mut ships_a);
}
pub fn parallel_shooting(
fleet_a: &mut [Ship],
fleet_b: &mut [Ship],
) {
let t1 = thread::spawn(move || unsafe {
shoot(&fleet_a, &mut fleet_b);
});
let t2 = thread::spawn(move || unsafe {
shoot(&fleet_b, &mut fleet_a);
});
t1.join().unwrap();
t2.join().unwrap();
}
hullandshield) while the attackers only have read access to the values being read (and crucially not be able to access thehullandshieldin any way).Vecwith an element in it. Thread one has a&to it, and takes&v[0]. Thread two has a&mutto it, and it later doesv.clear(). What happens when the first thread tries to use the reference? Does this help you understand why&mutaccess must be exclusive to all other access?