What happens when an Arc is cloned?

2019-04-18 17:55发布

问题:

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.

回答1:

[...] what is happening on let data = data.clone()?

Arc stands for Atomically Reference Counted. An Arc manages one object (of type T) and serves as a proxy to allow for shared ownership, meaning: one object is owned by multiple names. Wow, that sounds abstract, let's break it down!

Shared Ownership

Let's say you have an object of type Turtle