Share mutable state across threads in Rust by wrapping data in Arc<RwLock<T>> for safe concurrent access.
Use Arc<RwLock<T>> to share mutable state across threads safely by wrapping the data in an RwLock for synchronization and an Arc for reference counting.
use std::sync::{Arc, RwLock};
let data = Arc::new(RwLock::new(0));
let data_clone = Arc::clone(&data);
// Read access (multiple readers allowed)
let val = *data.read().unwrap();
// Write access (exclusive writer)
let mut guard = data_clone.write().unwrap();
*guard += 1;
Think of Arc as a shared ownership ticket that lets multiple threads hold a reference to the same data without deleting it prematurely. The RwLock acts like a bouncer at a club, allowing many people to look inside (read) at once but only letting one person change things (write) at a time to prevent chaos. You use this combination when you need multiple threads to safely update the same piece of information.