January 2019
Beginner to intermediate
554 pages
13h 31m
English
The preceding code can be made to work with the multi-threaded Arc type as follows:
// thread_arc.rsuse std::thread;use std::sync::Arc;fn main() { let nums = Arc::new(vec![0, 1, 2, 3, 4]); let mut childs = vec![]; for n in 0..5 { let ns = Arc::clone(&nums); let c = thread::spawn(move || { println!("{}", ns[n]); }); childs.push(c); } for c in childs { c.join().unwrap(); }}
In the preceding code, we simply replaced the wrapper of the vector from Rc to the Arc type. Another change is that, before we reference nums from a child thread, we need to clone it with Arc::clone(), which gives us an owned Arc<Vec<i32>> value that refers to the same Vec. With that change, our program compiles and provides safe access to the ...
Read now
Unlock full access