I am learning concurrency and want to clarify my understanding on the following code example from the Rust book. Please correct me if I am wrong.
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
fn main() {
let data = Arc::new(Mutex::new(vec![1, 2, 3]));
for i in 0..3 {
let data = data.clone();
thread::spawn(move || {
let mut data = data.lock().unwrap();
data[0] += i;
});
}
thread::sleep(Duration::from_millis(50));
}
What is happening on the line let data = data.clone()
?
The Rust book says
we use
clone()
to create a new owned handle. This handle is then moved into the new thread.
What is the new "owned handle"? It sounds like a reference to the data?
Since clone
takes a &self
and returns a Self
, is each thread modifying the original data instead of a copy? I guess that is why the code is not using data.copy()
but data.clone()
here.
The data
on the right side is a reference, and the data
on the left is a owned value. There is a variable shadowing here.