Arc unwrap_or_clone Takes The Last Handle

Arc::unwrap_or_clone moves the inner value out when only one handle remains and falls back to a clone when other handles still exist.

RustData Integrity

Code

rustsnippet
23 lines
use std::sync::Arc;
use std::thread;

fn main() {
    let shared: Arc<Vec<i32>> = Arc::new(vec![10, 20, 30]);

    // worker 线程持有克隆期间共享计数为 2
    let worker = {
        let shared = Arc::clone(&shared);
        thread::spawn(move || shared.iter().sum::<i32>())
    };
    let total = worker.join().unwrap();

    // after join only the last handle remains: move the value out, zero clones
    let owned = Arc::unwrap_or_clone(shared);
    println!("total {total}, owned {owned:?}");

    // with other handles present it falls back to a clone
    let a = Arc::new(vec![1, 2, 3]);
    let b = Arc::clone(&a);
    let copy = Arc::unwrap_or_clone(a);
    println!("copy {copy:?}, shared handle {b:?}");
}

How it works

The snippet is organized around the function main.

What to watch for

  • The package manager never enters the picture for this snippet.

Using it

The signature you will call most reads fn main()

Look for the total, copy prefixes once the file starts running; each one ties a printed line to the step that produced it.

The key statements, annotated

thread::spawn(move || shared.iter().sum::<i32>())
};
let owned = Arc::unwrap_or_clone(shared);
let total = worker.join().unwrap();

Interactive Tools for This Topic

FAQ

What does Arc unwrap_or_clone Takes The Last Handle print when run?
Running the file directly is enough — expect labeled output lines such as `total`, `copy`.