Mutex and Arc
A channel passes values from hand to hand. But sometimes several workers need the same thing: a shared counter, a shared order list. If two threads change one number at the same time with no order at all, one change can overwrite the other. This is called a data race, and safe Rust does not allow it.
In a workshop, shared things sit in a storeroom, and there is only one key to it. Whoever takes the key goes in and works with the shelves. The others wait at the door. On the way out, the worker returns the key, and the next one takes it.
Mutex: the one storeroom key
A mutex, the type Mutex<T>, hides a value inside. The only way to reach it is through lock() — that is "taking the key".
use std::sync::Mutex;
fn main() {
let m = Mutex::new(5);
{
let mut g = m.lock().unwrap();
*g += 1;
println!("{g}"); // 6
}
println!("{}", m.lock().unwrap()); // 6
}Let's go through the example line by line:
Mutex::new(5)puts5into the storeroom.m.lock()takes the lock. The method takes&self, somneeds nomut. It returns aResult, andunwraptakes a guard out of it — a value of typeMutexGuard.- The value is read and changed through the guard:
*g += 1, as through a mutable reference. We change the number throughg, sogis declared withmut. println!("{g}")prints the value behind the guard:6.- At
}the guard is dropped, and the lock is released by itself. - The last line takes the lock again and prints
6.
Arc: a shared pass
The mutex has to be handed to several threads. But move moves a value into one closure, and the second thread gets nothing. You need a shared owner.
You already know Rc — a book with a reader count on its card. For threads it has a twin, Arc: a shared pass with a counter. Arc::clone(&m) does not copy the mutex; it issues one more pass to the very same one and adds 1 to the count. What sets Arc apart is that it changes the count with the processor's atomic operations: such a change happens in one indivisible step, and another thread cannot cut in halfway. So two threads cannot corrupt the count, even when they clone a pass at the same moment.
Each part answers its own question:
Arc— who owns the value;Mutex— who is changing it right now.
Both types live in the module std::sync, and one line makes their names available: use std::sync::{Arc, Mutex}; — the curly braces list several names from one module.
When the lock is released
The main rule of a mutex: the lock is held while the guard is alive, and it is released by itself when the guard goes out of scope. Step through the program and watch two things: where the guard is now and what the second thread is waiting for.
1use std::sync::{Arc, Mutex};2use std::thread;3 4fn main() {5 let m = Arc::new(Mutex::new(0));6 let m2 = Arc::clone(&m);7 let h = {8 let mut g = m.lock().unwrap();9 let h = thread::spawn(move || {10 let mut g2 = m2.lock().unwrap();11 *g2 += 10;12 println!("thread: {g2}");13 });14 *g += 1;15 println!("main: {g}");16 h17 };18 h.join().unwrap();19 let g = m.lock().unwrap();20 println!("total: {g}");21}
Arc::clone issued a second pass to the same mutex; the lock is free.
So, step by step through the trace:
- The thread reached
lock, butmainhad the key, and the thread waited. - The lock was released not after the last use of
gbut at the block's closing brace, where the guard was dropped. - Only then did the thread take the lock and see
1, not0.
The practical lesson: keep a guard in a small block. While it is alive, the other threads stand at the door.
A counter in several threads
Let's put it all together: three threads add their 1, 2 and 3 to a shared number.
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let total = Arc::new(Mutex::new(0));
let mut handles = Vec::new();
for i in 1..=3 {
let t = Arc::clone(&total);
let h = thread::spawn(move || *t.lock().unwrap() += i);
handles.push(h);
}
handles.into_iter().for_each(|h| h.join().unwrap());
println!("{}", total.lock().unwrap()); // 6
}What happens here:
- Each step of the loop gives a thread its own pass
tto one and the same mutex. *t.lock().unwrap() += itakes the lock, addsiand lets go at once: the guard here is temporary and is dropped at the end of the line.iis aCopyvalue, somoveputs a copy of it into the thread.- The threads take the lock one at a time, and no addition is lost.
for_eachcalls the closure for every item of the iterator — the same as afor h in handlesloop. Here it callsjoinfor each thread.- The printing comes after every
join, so the total is always6.
Common mistake
The guard is declared without mut, and then the value is changed through it:
use std::sync::Mutex;
fn main() {
let m = Mutex::new(5);
let g = m.lock().unwrap(); // ✗
*g += 1;
println!("{g}");
}error[E0596]: cannot borrow `g` as mutable, as it is not declared as mutableThe program does not compile. m needs no mut, because lock takes &self. The guard does need mut: *g += 1 changes the value through it. The fix is let mut g = m.lock().unwrap();.
Key points
lock()takes&selfand returns aMutexGuard; the value is read and changed through it.- The lock is released when the guard goes out of scope, not after its last use.
Arc::cloneissues one more pass to the same value;Arc<Mutex<T>>gives threads a shared mutable counter.