Sub topic 8
Keeping critical sections short
This chapter assumes you can already share a counter or a Vec with Arc<Mutex<T>>. It also assumes you know that lock() returns a guard that unlocks when it is dropped.
What a critical section is
A critical section is the stretch of code that runs while a thread holds a lock. Only one thread can be inside it at a time. Every other thread that calls lock() on the same mutex waits until the guard is dropped.
The guard lives until the end of its scope. Rust does not release it after your last use of the data. So the length of the critical section is the distance from lock() to the closing brace, or to an explicit drop.
The cost of a long critical section
Here, each thread locks first and then does slow work, simulated with sleep.
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
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 mut guard = log.lock().unwrap();
thread::sleep(Duration::from_millis(100)); // slow work while locked
guard.push(id * 10);
})
})
.collect();
for handle in handles {
handle.join().unwrap();
}
println!("{}", log.lock().unwrap().len());
}The program is correct, but the four sleeps run one after another, so it takes about 400 ms. The threads add no parallelism, because the slow work is inside the lock.
Do the work first, lock last
Compute the result without the lock. Take the lock only to touch the shared data, and release it right away.
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);
}This prints [0, 10, 20, 30]. The inner block makes the end of the critical section visible. Here the block is only a style choice. It matters when more code follows the push.
Ways to end a guard early
- A temporary guard. In
log.lock().unwrap().push(result);the guard is a temporary. It is dropped at the end of that statement. - An inner block. Use braces, as above, when you need the guard for several statements.
drop(guard). Call it when the guard's scope is the whole function and you are finished with the data partway through.- Copy out what you need. Read a value or clone it, let the guard go, and then work on your own copy.
What not to do while locked
Avoid these inside a critical section:
- Sleeping, file or network I/O, and other blocking calls.
- Joining another thread.
- Locking a second mutex without a defined order. This risks deadlock, which a later chapter covers.
- Calling unknown code, such as a user-supplied closure, which may do any of the above.
A short critical section also shrinks the window in which a panic can poison the mutex.
Exercise
A worker does let mut g = stats.lock().unwrap(); let parsed = parse(&line); g.total += parsed.len(); where parse is slow and does not use stats. Rewrite it so the lock is held for less time.
Show answer
Parse first, then lock only for the update: let parsed = parse(&line); stats.lock().unwrap().total += parsed.len();. The slow parse call now runs outside the lock, so several threads can parse at once. The guard is a temporary, so it is released at the end of the statement.