Arc lets multiple owners share the same value. Cloning the Arc adds owners without cloning the inner data.

Program

Play the program to choose how many worker handles share one label.

workers
arc_shared_label.rs
Replay: real traced execution (multi-file project)
use std::sync::Arc;

fn main() {
    let workers = 2;
    let label = Arc::new("cache");
    let handles: Vec<_> = (0..workers).map(|_| Arc::clone(&label)).collect();
    println!("workers={} strong={}", handles.len(), Arc::strong_count(&label));
}
use std::sync::Arc;

fn main() {
    let workers = 1;
    let label = Arc::new("cache");
    let handles: Vec<_> = (0..workers).map(|_| Arc::clone(&label)).collect();
    println!("workers={} strong={}", handles.len(), Arc::strong_count(&label));
}
use std::sync::Arc;

fn main() {
    let workers = 3;
    let label = Arc::new("cache");
    let handles: Vec<_> = (0..workers).map(|_| Arc::clone(&label)).collect();
    println!("workers={} strong={}", handles.len(), Arc::strong_count(&label));
}
  1. workers ← 2, label ← "cache", handles ← ["cache", "cache"]

    3fn main() {4    let worker→ 2s = 2; //@workers=2, 1, 35    let labe→ "cache"l = Arc::new("cache");6    let handle→ ["cache", "cache"]s: Vec<_> = (0..worker2s).map(|_| Arc::clone(&label)).collect();7    println!("workers={} strong={}", handles.len(), Arc::strong_count(&label));8}
    outputworkers=2 strong=3
  1. workers ← 1, label ← "cache", handles ← ["cache"]

    3fn main() {4    let worker→ 1s = 1;5    let labe→ "cache"l = Arc::new("cache");6    let handle→ ["cache"]s: Vec<_> = (0..worker1s).map(|_| Arc::clone(&label)).collect();7    println!("workers={} strong={}", handles.len(), Arc::strong_count(&label));8}
    outputworkers=1 strong=2
  1. workers ← 3, label ← "cache", handles ← ["cache", "cache", "cache"]

    3fn main() {4    let worker→ 3s = 3;5    let labe→ "cache"l = Arc::new("cache");6    let handle→ ["cache", "cache", "cache"]s: Vec<_> = (0..worker3s).map(|_| Arc::clone(&label)).collect();7    println!("workers={} strong={}", handles.len(), Arc::strong_count(&label));8}
    outputworkers=3 strong=4
Arc `Arc` is an atomically reference-counted pointer for shared ownership.
clone `Arc::clone` creates another owner of the same inner value.
strong_count `strong_count` reports how many strong owners currently exist.