Sub topic 8
Keeping Critical Sections Short
This chapter assumes you can use Arc<Mutex<T>> to share data between threads and know that lock() returns a guard that unlocks when it is dropped. It also assumes you know thread::spawn, move closures and unwrap. The chapter covers how long a thread should hold a lock, how to shorten that time, and which mistakes keep a lock held longer than you meant.
What a critical section is
A critical section is the stretch of code during which a thread holds a lock. With a Mutex, it runs from the successful lock() call until the MutexGuard is dropped. While one thread is inside, every other thread that calls lock() on the same mutex blocks.
Correctness only needs the critical section to cover the code that reads or writes the protected data. The compiler does not enforce that, and it does not warn you when a guard lives too long. The program stays correct, but the threads run one after another.
Why length matters
A mutex turns the code inside it into a serial section. If four threads each spend 100 ms inside the lock, the total is about 400 ms no matter how many cores you have. The same work done outside the lock can overlap across threads.
The example below measures this. Both variants do 100 ms of simulated work per thread. The first does the work while holding the guard. The second does the work first and locks only for the push.
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::{Duration, Instant};
fn run(hold_lock_during_work: bool) -> Duration {
let log = Arc::new(Mutex::new(Vec::new()));
let start = Instant::now();
let handles: Vec<_> = (0..4)
.map(|id| {
let log = Arc::clone(&log);
thread::spawn(move || {
if hold_lock_during_work {
let mut guard = log.lock().unwrap();
thread::sleep(Duration::from_millis(100));
guard.push(id);
} else {
thread::sleep(Duration::from_millis(100));
log.lock().unwrap().push(id);
}
})
})
.collect();
for handle in handles {
handle.join().unwrap();
}
start.elapsed()
}
fn main() {
println!("work inside lock: {:?}", run(true));
println!("work outside lock: {:?}", run(false));
}On a typical machine the first line shows a little over 400 ms and the second a little over 100 ms. The exact numbers vary from run to run, but the ratio stays close to the thread count.
Technique 1: do the work first, lock last
Compute results into local variables, which no other thread can see, and take the lock only to publish them. The chapter's reference example does this:
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let log = Arc::new(Mutex::new(Vec::new()));
let handles: Vec<_> = (0..4)
.map(|id| {
let log = Arc::clone(&log);
thread::spawn(move || {
let result = id * 10; // slow work happens without the lock
{
let mut guard = log.lock().unwrap();
guard.push(result);
} // guard dropped here, lock released
})
})
.collect();
for handle in handles {
handle.join().unwrap();
}
let mut values = log.lock().unwrap().clone();
values.sort();
println!("{:?}", values);
}The program prints [0, 10, 20, 30]. The inner block ends the guard's scope right after the push. Without the block, the guard would live to the end of the closure, which is harmless here but becomes a problem as soon as more code follows.
Technique 2: end the guard early
You have two ways to release a lock before the end of a function:
- Wrap the locked code in a block, as above. The guard drops at the closing brace.
- Call
drop(guard)explicitly. This is useful when the code after the release needs the guard's variable name to stay in scope, or when a block would be awkward.
use std::sync::Mutex;
fn main() {
let total = Mutex::new(0u64);
let mut guard = total.lock().unwrap();
*guard += 5;
drop(guard); // lock released; `guard` can no longer be used
let report = format!("working without the lock");
println!("{report}");
println!("total = {}", total.lock().unwrap());
}After drop(guard) the compiler rejects any further use of guard. That is a useful safety net, because you cannot touch the data without the lock by accident.
Technique 3: take the data out, then process it
When a thread needs to process shared data, copy or move the data out under the lock and work on the private copy. std::mem::take swaps the contents for the type's default value, so the lock is held only for the swap:
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let queue = Arc::new(Mutex::new(vec![1u32, 2, 3, 4]));
let q = Arc::clone(&queue);
let worker = thread::spawn(move || {
let batch = {
let mut guard = q.lock().unwrap();
std::mem::take(&mut *guard)
};
// Producers can push into `queue` again while we do this.
batch.iter().map(|n| n * n).sum::<u32>()
});
println!("sum of squares: {}", worker.join().unwrap());
println!("left in queue: {}", queue.lock().unwrap().len());
}This prints sum of squares: 30 and left in queue: 0. The slow part, the arithmetic, runs after the lock is gone. Cloning small values with .copied() or .clone() works the same way.
Gotchas that keep a guard alive
Temporaries live to the end of the statement
A guard created inside an expression is a temporary. It is dropped at the end of the enclosing statement, not at the end of the call that used it. In match and if let, the scrutinee (the expression being matched) counts as part of the statement, so the guard can stay alive through the entire block.
use std::collections::HashMap;
use std::sync::Mutex;
fn slow_lookup(key: &str) -> usize {
key.len() // stands in for expensive work
}
fn main() {
let cache: Mutex<HashMap<String, usize>> = Mutex::new(HashMap::new());
let key = "alpha";
// Bad: the guard from lock() lives for the whole match,
// so slow_lookup runs while the lock is held.
// match cache.lock().unwrap().get(key) {
// Some(v) => println!("hit {v}"),
// None => { slow_lookup(key); }
// }
// Good: copy the answer out in its own statement.
let cached = cache.lock().unwrap().get(key).copied();
let value = match cached {
Some(v) => v,
None => {
let v = slow_lookup(key);
cache.lock().unwrap().insert(key.to_string(), v);
v
}
};
println!("{value}");
}The let cached = ...; statement ends at the semicolon, which drops the guard. The match then runs on a plain Option<usize>. The rule for if let scrutinees changed in Rust edition 2024, where the temporary is dropped before the else branch. Copying the value into a let first works in every edition and makes the lock scope obvious.
Slow operations inside the lock
Treat these as red flags when you see them between lock() and the end of the guard's scope:
- File, network or database I/O.
thread::sleep,JoinHandle::join, or receiving from a channel.- Locking a second mutex, which is the road to deadlock (covered in a later chapter).
- Calling a callback or trait method you do not control. It may do any of the above.
The standard MutexGuard is also not Send, so holding one across an .await in async code is a compile error in most executors. The fix is the same: finish with the guard before awaiting.
Do not split an operation that must be atomic
Shorter is not always better. If two steps must happen as one unit, they belong in one critical section.
The cache example earlier has a milder version of this. Two threads can both miss, both call slow_lookup, and both insert. Here the result is the same, so the duplicate work is acceptable. If duplicate work were harmful, you would hold the lock across the lookup or use a different design, such as per-key state.
A short checklist
- Identify which statements touch the shared data. Only those belong in the critical section.
- Move computation, formatting, allocation and I/O before the lock or after the release.
- Bind the guard to the narrowest scope that works, using a block or
drop. - In
match,if letandwhile let, check whether a locking call in the scrutinee holds the guard longer than you meant. - Check that every invariant spanning multiple operations is still protected by one guard.
Exercise
This worker loop takes an item from a shared Mutex<Vec<String>> and processes it with a slow function. Why does it perform poorly with many workers, and how do you fix it? while let Some(item) = queue.lock().unwrap().pop() { slow_process(&item); }
Show answer
The guard is a temporary in the while let scrutinee, so it stays alive for the entire loop body. Every call to slow_process runs with the lock held, and the other workers cannot pop anything until it finishes. Fix it by popping in a separate statement so the guard drops at the semicolon: loop { let item = queue.lock().unwrap().pop(); match item { Some(item) => slow_process(&item), None => break } }. Now slow_process runs with no lock held, and the workers overlap.
Exercise
A thread updates a shared counter with let current = *counter.lock().unwrap(); let next = current + 1; *counter.lock().unwrap() = next;. Each lock is held briefly. Is this a good use of short critical sections?
Show answer
No. The read and the write use separate guards, so another thread can change the counter between them and one update is lost. The read-modify-write is one logical operation and must sit under a single guard: *counter.lock().unwrap() += 1;. For a plain counter, an atomic integer is a simpler alternative.