Wrap your data in Arc for shared ownership and Mutex for safe mutation, then clone the Arc to pass it to each thread.
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let data = Arc::new(Mutex::new(vec![1, 2, 3]));
let mut handles = vec![];
for _ in 0..3 {
let data_clone = Arc::clone(&data);
let handle = thread::spawn(move || {
let mut num = data_clone.lock().unwrap();
num.push(4);
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
println!("{:?}", *data.lock().unwrap());
}