use std::sync::{Arc, Mutex}; use std::thread; use std::time::Duration; struct Rule { id: i64, words: Vec, } struct Repo { version: i64, rules: Vec>>, } fn main() { let r0 = Arc::new(Mutex::new(Rule { id: 0, words: vec!["a".to_string(), "b".to_string(), "c".to_string()], })); let r1 = Arc::new(Mutex::new(Rule { id: 1, words: vec!["0".to_string(), "1".to_string(), "2".to_string()], })); let repo = Arc::new(Repo { version: 0, rules: vec![r0, r1], }); let mut handles = Vec::new(); let repo_for_read = Arc::clone(&repo); let handle1 = thread::spawn(move || { let repo = repo_for_read; let rs = repo.rules.clone(); thread::sleep(Duration::from_secs(2)); for r in rs.iter() { println!("{}", r.lock().unwrap().id); } }); handles.push(handle1); let repo_for_write = Arc::clone(&repo); let handle2 = thread::spawn(move || { thread::sleep(Duration::from_secs(1)); let mut rules = repo_for_write.rules.clone(); if let Some(r) = rules.get_mut(1) { let mut r = r.lock().unwrap(); r.id = 999; } rules.remove(1); if let Some(r) = rules.get_mut(0) { let mut r = r.lock().unwrap(); r.id = 1000; } }); handles.push(handle2); for handle in handles { handle.join().unwrap(); } }