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
:use std::sync::Arc; let num = Arc::new(10);
-
Cloning: Use
Arc::clone(&arc_instance)
to create another reference.let a = Arc::new(5); let b = Arc::clone(&a);
-
Sharing Between Threads:
use std::sync::Arc; use std::thread; let data = Arc::new(10); for _ in 0..5 { let data = Arc::clone(&data); thread::spawn(move || { println!("{:?}", data); }); }
-
Breaking Reference Cycles: Use
Weak
pointers to create non-owning references that won’t prevent deallocation.let arc_instance = Arc::new(10); let weak_ref = Arc::downgrade(&arc_instance);
-
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.