Share Data Between Threads in Rust with Arc and Mutex
Share mutable state across threads in Rust 1.85 with Arc and Mutex, see why Rc and a bare Mutex fail to compile, and how to keep lock guards short.

Rust will not let you share a mutable value between threads by accident. Try to hand the same Vec to two spawned threads and the compiler refuses before the program exists. That refusal is the point, and the fix is two standard library types that appear together so often they read as one phrase: Arc<Mutex<T>>. Arc gives several threads shared ownership of one value, and Mutex makes sure only one of them mutates it at a time. This post builds up to that pattern from the compile errors, using Rust 1.85 with edition 2024, explains each piece, and covers the habits that keep a lock guard from causing trouble. No earlier concurrency knowledge is assumed beyond knowing what a thread is.
Why the obvious attempt fails
Start with the most natural code: a counter, and two threads that each add to it.
use std::thread;
fn main() {
let mut count = 0;
let a = thread::spawn(|| {
count += 1;
});
let b = thread::spawn(|| {
count += 1;
});
a.join().unwrap();
b.join().unwrap();
println!("{count}");
}This does not compile. The compiler reports error E0373: the closure may outlive the current function, but it borrows count. A spawned thread can run for as long as the program does, so thread::spawn requires its closure to be 'static, which a borrow of a local variable is not. Adding move to the closures makes them own a copy of count, and then the program compiles but prints 0, because each thread incremented its own copy. Neither result is what you wanted.
To share one value you need shared ownership and a way to mutate through it safely. The ownership comes from Arc, the mutation from Mutex.
Arc: shared ownership across threads
Rc<T> is the standard reference-counted pointer, and it is the wrong tool here. Its reference count is a plain integer that two threads could update at once. The compiler knows, because Rc<T> does not implement the Send trait, and thread::spawn requires the closure and everything it captured to be Send. Try to move an Rc into a thread and you get error E0277: Rc<i32> cannot be sent between threads safely.
Arc<T>, the atomic reference-counted pointer, is the thread-safe counterpart. Cloning an Arc increments an atomic counter and gives you another handle to the same allocation. When the last handle is dropped, the value is freed. The Rust standard library documentation for std::sync::Arc describes it as a thread-safe reference-counting pointer.
Arc alone only gives shared, read-only access. You cannot get a &mut T out of an Arc<T> while other handles exist, because that would be two aliases with one mutable. So for shared mutation you need interior mutability that is safe across threads.
Mutex: one writer at a time
std::sync::Mutex<T> owns a value of type T and hands out access to it only through a lock. This differs from the C API in an important way: in Rust the mutex contains the data it protects, so you cannot touch the data without locking. There is no way to forget.
use std::sync::Mutex;
fn main() {
let m = Mutex::new(5);
{
let mut guard = m.lock().unwrap();
*guard += 1;
}
println!("{:?}", m);
}Mutex { data: 6, poisoned: false, .. }lock() returns a Result<MutexGuard<T>, PoisonError<...>>. The guard dereferences to the value, so *guard += 1 changes the contents. When the guard goes out of scope the lock is released automatically. The unwrap() handles poisoning, which happens when a thread panicked while holding the lock. That case is covered in a later post in this cluster, and for now unwrap() is the usual choice because a poisoned mutex normally means the program is already in trouble.
Put them together
Wrap the mutex in an Arc, clone the Arc once per thread, and move each clone into its thread.
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let counter = Arc::new(Mutex::new(0u32));
let mut handles = Vec::new();
for _ in 0..4 {
let counter = Arc::clone(&counter);
handles.push(thread::spawn(move || {
for _ in 0..1000 {
let mut n = counter.lock().unwrap();
*n += 1;
}
}));
}
for h in handles {
h.join().unwrap();
}
println!("total = {}", *counter.lock().unwrap());
}total = 4000Read it slowly, because every part is doing a job. Arc::new(Mutex::new(0)) creates the one shared allocation. Inside the loop, let counter = Arc::clone(&counter) shadows the outer name with a fresh handle, so the move closure takes ownership of its own handle and the original stays in main. Each thread locks, increments and drops the guard at the end of the inner loop body. After joining, main locks once more to read the total.
The result is always 4000. If you delete the Mutex and use Arc<u32>, the compiler rejects *n += 1, since you cannot mutate through a shared Arc. The data race is a compile error rather than a runtime surprise, which is what Rust's Send and Sync rules are for.
Why Arc::clone and not counter.clone()
Both work, and the standard library docs recommend the explicit form Arc::clone(&a). The reason is readability: counter.clone() looks like a deep copy of the data, while Arc::clone makes it plain that you are only bumping a reference count. It is a convention, not a requirement.
Keep the guard short-lived
The guard holds the lock for as long as it lives. A common mistake is to keep it alive across slow work, or to hold it in a variable when you only needed one operation.
use std::sync::{Arc, Mutex};
use std::time::Duration;
use std::thread;
fn main() {
let log = Arc::new(Mutex::new(Vec::<String>::new()));
let worker = {
let log = Arc::clone(&log);
thread::spawn(move || {
for i in 0..3 {
let line = format!("job {i}");
thread::sleep(Duration::from_millis(10));
log.lock().unwrap().push(line);
}
})
};
worker.join().unwrap();
println!("{:?}", log.lock().unwrap());
}["job 0", "job 1", "job 2"]The sleep happens before the lock, and log.lock().unwrap().push(line) is a single expression, so the guard is a temporary that is dropped at the end of the statement. Other threads can lock the vector while this thread sleeps. If you wrote let mut g = log.lock().unwrap(); above the sleep, the lock would be held for the whole 10 milliseconds and every other thread would wait.
There is a subtler trap. Holding a guard in a variable and then calling a function that locks the same mutex deadlocks the thread. Rust's Mutex is not reentrant, and the standard library documentation says that locking a mutex already held by the current thread might deadlock or panic. Drop the guard first with drop(guard) or end its scope with a block.
Reading with less ceremony
When many threads mostly read and rarely write, Arc<RwLock<T>> lets any number of readers hold the lock at once. It adds complexity and its own deadlock rules, so start with Mutex and switch only when contention proves a problem. For a plain counter, AtomicU32 inside an Arc avoids the lock entirely and is the right choice when the shared state is a single integer.
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::Arc;
use std::thread;
fn main() {
let counter = Arc::new(AtomicU32::new(0));
let handles: Vec<_> = (0..4)
.map(|_| {
let c = Arc::clone(&counter);
thread::spawn(move || {
for _ in 0..1000 {
c.fetch_add(1, Ordering::Relaxed);
}
})
})
.collect();
for h in handles {
h.join().unwrap();
}
println!("total = {}", counter.load(Ordering::Relaxed));
}total = 4000Relaxed ordering is enough here because the joins already order the final read after the increments. As soon as two values must change together, go back to a Mutex around a struct.
Where this pattern stops
Arc<Mutex<T>> is the general tool, not always the best one. If threads can work on separate pieces of data, give each its own piece and merge at the end, or use scoped threads from std::thread::scope, which let threads borrow local data without Arc at all. If threads pass work to each other, a channel from std::sync::mpsc often expresses the program better than shared state. And a long-lived global lock invites contention, so keep what is inside the mutex small.


