liveBook · Manning

Arc

As explained in Code Like a Pro in Rust

Arc is a Rust thread-safe reference-counted smart pointer for shared ownership of a value across threads.

`Arc` is a reference-counted smart pointer for shared ownership across threads. Cloning the pointer increments an atomic reference count; dropping a clone decrements it, and the allocation can be released when the count reaches zero. Use `Rc` instead when ownership stays within one thread: atomic operations cost more than ordinary counter updates. section 5.6

`Arc` supports sharing, not mutation by itself. Pair it with `Mutex` or `RwLock` when shared data must change. `Arc::make_mut()` offers a different choice: clone-on-write mutation rather than synchronizing mutations to one shared value. section 5.10 section 5.7

A counter shared by tests

A test can clone an `Arc<AtomicI32>` with `Arc::clone(&COUNT)` and increment the counter with `fetch_add`. A direct `static COUNT: Arc<AtomicI32> = Arc::new(...)` fails in the shown setup because that initializer cannot run in a static; `lazy_static!` supplies runtime initialization. If the counter only needs to be a global atomic, use a lazily initialized `AtomicI32` without `Arc`. section 6.5

#[cfg(test)]
mod tests {
    use lazy_static::lazy_static;
    use std::sync::atomic::{AtomicI32, Ordering};
    use std::sync::Arc;
    lazy_static! {                                                        #1
        static ref COUNT: Arc<AtomicI32> = Arc::new(AtomicI32::new(0));   #2
    }
 
    #[test]
    fn test_count() {
        let count = Arc::clone(&COUNT);
        count.fetch_add(1, Ordering::SeqCst);
    }
}

Shows `Arc::clone` in a parallel-test counter and the `lazy_static!` initialization needed for the demonstrated `Arc` global. section 6.5

Choose `Arc` when multiple threads need ownership of the same value. Check separately whether the value needs synchronized mutation, clone-on-write mutation, or neither; do not add reference counting merely because a value is global. section 5.10 section 5.7 section 6.5

How Code Like a Pro in Rust covers it

How deep it goes
Explains reference-count changes and atomic cost, then works through global initialization; stops short of implementing Arc.
Examples
Uses a parallel-test counter, compiler errors, `Arc::clone`, and `lazy_static!` to expose an initialization pitfall.
What it assumes
Assumes Rust pointer and trait familiarity; defines Send and Sync when the shared-state example needs them.
What you can do after
Apply it via Rust's `Arc` when ownership crosses threads, choosing synchronization or clone-on-write separately.
How it connects
Connects Rc, Send, Sync, Mutex, RwLock, atomic integers, and clone-on-write.

Also explained in

Compare how 2 books explain Arc →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Code Like a Pro in Rust. The section links point to the parts of the book it draws on.