January 2019
Beginner to intermediate
554 pages
13h 31m
English
We'll take a look at a sample program where five threads push data to a shared Vec. The following program tries to do the same:
// thread_mut.rsuse std::thread;use std::sync::Arc;fn main() { let mut nums = Arc::new(vec![]); for n in 0..5 { let mut ns = nums.clone(); thread::spawn(move || { nums.push(n); }); }}
We have the same nums wrapped with Arc. But we cannot mutate it, as the compiler gives the following error:

This doesn't work as cloning Arc hands out immutable reference to the inner value. To mutate data from multiple threads, we need to use a type that provides shared mutability just like RefCell ...
Read now
Unlock full access