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),Arcuses atomic operations to manage its reference count, making it suitable for concurrent environments. - Immutability: Data inside an
Arcis immutable by default. For mutable access across threads, useMutexorRwLock. - Cloning: Cloning an
Arccreates 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
Weakpointers 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:
Arcsupports conversion to and from raw pointers usinginto_rawandfrom_raw.
By using Arc, Rust enables safe shared data access across threads, a powerful feature for concurrent programming.