Arc Strong Count Tracks Owners
Watch Arc::strong_count rise and fall as clones are created and dropped, and use Arc::ptr_eq to prove two handles share one allocation.
Code
use std::sync::Arc;
fn main() {
let shared = Arc::new(String::from("metrics"));
// strong_count counts live owners, not borrows
println!("initial: {}", Arc::strong_count(&shared));
let second = Arc::clone(&shared);
println!("after clone: {}", Arc::strong_count(&shared));
println!("same allocation: {}", Arc::ptr_eq(&shared, &second));
{
let third = Arc::clone(&shared);
println!("inner scope: {}", Arc::strong_count(&shared));
drop(third);
}
println!("after scope: {}", Arc::strong_count(&shared));
drop(second);
println!("after drop: {}", Arc::strong_count(&shared));
println!("value still readable: {}", shared.len());
}How the snippet works
Count the function main as the entire surface area of Arc Strong Count Tracks Owners.
Using it
The primary signature is fn main()
Each run prints the 7 labeled blocks initial:, after clone:, same allocation:, inner scope:, after scope:, after drop:, value still readable: in source order.
Key statements
let shared = Arc::new(String::from("metrics"));
let second = Arc::clone(&shared);
let third = Arc::clone(&shared);
Interactive Tools for This Topic
FAQ
- What does Arc Strong Count Tracks Owners print when run?
- Execute the whole file; each printed line is prefixed with a label like `initial:`, `after clone:`, `same allocation:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.