Sharing data between threads in Rust with Arc and Mutex

When several threads need to change the same data, Rust won’t compile the program until you say how that access is coordinated. The standard library gives you a few tools for this in std::sync: Mutex and RwLock for locking, atomic types for single values, and channels (mpsc) for passing data instead of sharing it.
This post builds a small program where five threads update one shared Vec through an Arc<Mutex<Vec<i32>>>.
What Arc and Mutex each do
Section titled “What Arc and Mutex each do”Mutex<T>allows one thread at a time to access theTinside.lock()blocks until the lock is free and returns a guard; the lock is released when the guard is dropped.Arc<T>is a reference-counted pointer that is safe to share across threads. AMutexon its own can’t be moved into several threads, so you wrap it in anArcand give each thread a clone of theArc.
Without the Mutex, the compiler rejects mutation through an Arc. Without the Arc, the compiler rejects moving the same value into more than one thread::spawn closure.
Project setup
Section titled “Project setup”cargo new mutex-democd mutex-democargo add randThe rand crate is only used to pick a random index. This example was written against rand 0.10, where rand::random_range uses the thread-local generator.
The program
Section titled “The program”Replace src/main.rs with:
use std::sync::{Arc, Mutex};use std::thread;
fn main() { // Ten counters, all starting at zero. let data = Arc::new(Mutex::new(vec![0; 10]));
let mut handles = Vec::new();
for i in 0..5 { let data = Arc::clone(&data); let handle = thread::spawn(move || { for _ in 0..100 { let mut data = data.lock().unwrap(); let index = rand::random_range(0..data.len()); data[index] += i; } // the guard is dropped here each iteration, releasing the lock }); handles.push(handle); }
for handle in handles { handle.join().unwrap(); }
let data = data.lock().unwrap(); let total: i32 = data.iter().sum(); println!("{:?}", *data); println!("total = {total}");}How it works:
vec![0; 10]is the shared data, moved into aMutexand then into anArc.- Each loop iteration clones the
Arc(this only increments a reference count) and moves the clone into a new thread. - Inside the thread,
data.lock()returns aMutexGuard, which dereferences to theVec. The guard is created inside the innerforloop, so the lock is held for one update at a time and the threads interleave. lock()returns aResultbecause a mutex becomes poisoned if a thread panics while holding it.unwrap()is fine for a demo; in real code decide whether to propagate the error or recover the data withinto_inner()on thePoisonError.- After
join()ing every thread,mainlocks the mutex one last time to print the result.
Running it
Section titled “Running it”cargo runThe distribution changes on every run, because the indices are random and the threads are scheduled in a different order each time:
[93, 112, 105, 87, 120, 96, 101, 94, 88, 104]total = 1000The total is always 1000: thread i adds i a hundred times, and 100 × (0 + 1 + 2 + 3 + 4) = 1000. That fixed total is the point of the mutex. No update is lost even though five threads are writing to the same Vec.
Print *data (the Vec behind the guard) rather than the Arc itself. Debug-printing Arc<Mutex<_>> gives you something like Mutex { data: [...], poisoned: false, .. }.
Gotchas and alternatives
Section titled “Gotchas and alternatives”- Keep critical sections short. Holding a guard across slow work (I/O, sleeping, another lock) blocks every other thread. If you need the value after unlocking, copy it out and drop the guard first.
- Lock ordering. If code ever holds two mutexes at once, always take them in the same order, or two threads can deadlock waiting on each other. Rust’s type system prevents data races, but not deadlocks.
- Atomics for single numbers. If the shared state is a single counter,
AtomicUsize::fetch_addavoids locking entirely. RwLockfor read-heavy data. It allows many readers or one writer at a time.- Scoped threads. If the threads don’t outlive the function,
std::thread::scopelets them borrow aMutexfrom the stack, so you don’t need theArc. - Channels. If threads only produce results for one consumer, sending values over
std::sync::mpscis often simpler than sharing a structure.
Further reading
Section titled “Further reading”© 2026 David Li · Home · Blog · RSS ·Classic site · Built with Astro, Starlight and three.js · Logos:Font Awesome Free (CC BY 4.0)