January 2019
Beginner to intermediate
554 pages
13h 31m
English
Having explored the basics of Mutex in single threaded contexts, we'll revisit the example from the previous section. The following code modifies a value using a Mutex wrapped in an Arc from the multiple threads:
// arc_mutex.rsuse std::sync::{Arc, Mutex};use std::thread;fn main() { let vec = Arc::new(Mutex::new(vec![])); let mut childs = vec![]; for i in 0..5 { let mut v = vec.clone(); let t = thread::spawn(move || { let mut v = v.lock().unwrap(); v.push(i); }); childs.push(t); } for c in childs { c.join().unwrap(); } println!("{:?}", vec);}
In the preceding code, we created a Mutex value in m. We then spawn a thread. The output on your machine may vary.
Calling lock on a mutex will block other threads ...
Read now
Unlock full access