arc.md (2272B)
1 # Arc 2 3 In Rust, Arc is a smart pointer type that provides thread-safe, shared ownership 4 of data on the heap. Itβs used when multiple threads need to own the same value 5 at the same time. 6 7 ## Core idea 8 9 - Arc stands for Atomically Reference Counted. 10 11 - Type: std::sync::Arc<T>. 12 13 - Cloning an Arc<T> creates another handle to the same data and increments an 14 internal atomic reference count. 15 16 - When the last Arc<T> for a value is dropped, the data is deallocated. 17 18 ### Question: What "Atomically" actually mean in Arc? 19 20 The "atomically" refers specifically to how the reference count itself is 21 incremented and decremented, not to blocking other threads from reading. 22 23 An atomic operation is a CPU-level instruction that completes entirely as a 24 single, indivisible step, with no possibility of another thread observing it in 25 a half-finished state. So when two threads clone or drop an Arc simultaneously, 26 the reference count updates cannot interleave or corrupt each other. 27 28 ### Question: Does it mean that "another thread cannot read [the reference count] while one thread is reading it."? 29 30 No, this is the description of a mutex/lock, not an atomic operation. 31 32 The key distinction between Arc and Mutex/Lock: 33 34 | Mechanism | How it works | Blocking? | 35 | :------------------- | :----------------------------------------------------------------- | :---------------------------------- | 36 | **Mutex** | Only one thread accesses data at a time; others wait | Yes β threads are blocked | 37 | **Atomic operation** | The CPU guarantees the operation is indivisible; no waiting needed | No β threads don't block each other | 38 39 Atomic operations use special CPU instructions (like `fetch_add` and 40 `fetch_sub`) that make the increment/decrement happen in one uninterruptible 41 step. Multiple threads can operate concurrently β they just can't _partially_ 42 observe each other's changes.[^3] 43 44 ### Question: What Arc does NOT guarantee? 45 46 Arc only makes the **reference count** thread-safe, it does not make the 47 underlying datat T thread-safe. That's why is you need multiple thread to mutate 48 the shared data, you still need `Arc<Mutex<T>>` or `Arc<RwLock<T>>`