Wrap your data in Arc<T> to share ownership across threads and Mutex<T> if the data needs to be mutable. This combination allows multiple threads to safely read or write the same data without violating Rust's ownership rules.
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());
}