Introduction to Arc
in Rust
Arc
, or Atomically Reference Counted, is a thread-safe, reference-counting pointer in Rust. It allows multiple ownership of data across threads by managing a shared reference to heap-allocated data. When the last Arc
instance is dropped, the value is automatically deallocated.
Key Features
- Thread Safety: Unlike
Rc
(Reference Counted),Arc
uses atomic operations to manage its reference count, making it suitable for concurrent environments. - Immutability: Data inside an
Arc
is immutable by default. For mutable access across threads, useMutex
orRwLock
. - Cloning: Cloning an
Arc
creates another pointer to the same data without duplicating the data.
Basic Usage
-
Creating an
Arc
: -
Cloning: Use
Arc::clone(&arc_instance)
to create another reference. -
Sharing Between Threads:
-
Breaking Reference Cycles: Use
Weak
pointers to create non-owning references that won’t prevent deallocation. -
Converting to Raw Pointers:
Arc
supports conversion to and from raw pointers usinginto_raw
andfrom_raw
.
By using Arc
, Rust enables safe shared data access across threads, a powerful feature for concurrent programming.