Don't wrap atomic types in Arc unless you need to share ownership across multiple owners. Atomic types like AtomicBool, AtomicU64, etc. are already thread-safe and can be used directly in structs that will be wrapped in Arc at a higher level.
Don’t wrap atomic types in Arc unless you need to share ownership across multiple owners. Atomic types like AtomicBool, AtomicU64, etc. are already thread-safe and can be used directly in structs that will be wrapped in Arc at a higher level.
Using Arc
Example of the anti-pattern:
struct Impl {
sender: mpsc::SyncSender<Vec<u8>>,
write_shutdown: Arc<std::sync::atomic::AtomicBool>, // Unnecessary Arc
}
Preferred approach:
struct Impl {
sender: mpsc::SyncSender<Vec<u8>>,
write_shutdown: std::sync::atomic::AtomicBool, // Direct atomic type
}
// Wrap the entire struct in Arc when sharing is needed
let impl_instance = Arc::new(Impl::new(...));
This reduces memory overhead, eliminates unnecessary heap allocation, and simplifies the code while maintaining the same thread safety guarantees.
Enter the URL of a public GitHub repository