liveBook · Manning

Arc

As explained in Learn Rust in a Month of Lunches

Arc is Rust's atomically reference-counted smart pointer for sharing ownership of a value safely across threads.

Arc is Rust’s atomically reference-counted smart pointer. It lets multiple threads share ownership of one value safely. “Atomic” means an operation finishes as a whole, so another thread cannot observe it halfway through. section 12.3

Use Arc when several threads need the same owned value. Create it with Arc::new, then make additional owners with Arc::clone. For shared mutable data, combine Arc with Mutex: Arc shares ownership, while Mutex controls access to the value. section 12.3

Sharing a counter between threads

use std::sync::{Arc, Mutex}; let my_number = Arc::new(Mutex::new(0)); let cloned_1 = Arc::clone(&my_number); let cloned_2 = Arc::clone(&my_number); // Each thread locks its clone before incrementing. *cloned_1.lock().unwrap() += 1; *cloned_2.lock().unwrap() += 1; After both threads finish, the protected counter contains the combined updates. The example uses move closures so each thread receives its Arc clone. section 12.3

Arc is similar to Rc, but it is designed for threads. Prefer Rc when only one thread is involved because it is faster; choose Arc when ownership crosses thread boundaries. section 12.0 section 12.3

How Learn Rust in a Month of Lunches covers it

How deep it goes
Defines atomic operations and demonstrates cloning, locking, spawning, joining, and repeated shared-counter updates.
Examples
Uses Arc<Mutex<i32>> counters, two-thread increments, ten-thread loops, and helper functions that construct and clone Arcs.
What it assumes
Assumes familiarity with Rc and multiple threads while defining atomic operations and demonstrating Arc usage.
What you can do after
Build shared counters with Arc, Mutex, spawned threads, cloned owners, and joined handles.
How it connects
Connects Arc with Rc, Mutex, threads, atomic operations, closures, and ownership.

Also explained in

Compare how 2 books explain Arc →

Related concepts

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