Sub topic 13
Scoped threads: sharing without Arc
This chapter assumes you know ownership, borrowing and lifetimes, move closures, and thread::spawn with JoinHandle. It also assumes you have used Arc<Mutex<T>> to share state.
Why `thread::spawn` needs Arc
thread::spawn requires its closure to be 'static. The compiler cannot know when a spawned thread ends, so the closure may not borrow local variables. The thread could outlive the stack frame that owns them. That is why the earlier examples wrapped data in Arc and gave each thread a clone.
Often you do not need that freedom. If you spawn threads, do some work, and wait for all of them before moving on, every thread ends before the data goes away. Scoped threads let you tell the compiler this.
How `thread::scope` works
std::thread::scope takes a closure that receives a scope handle, usually named s. Threads started with s.spawn may borrow anything that outlives the scope. Before thread::scope returns, it joins every thread that has not been joined yet. Because of this guarantee, the 'static requirement is dropped.
use std::sync::Mutex;
use std::thread;
fn main() {
let total = Mutex::new(0);
thread::scope(|s| {
for i in 1..=4 {
let total = &total;
s.spawn(move || {
*total.lock().unwrap() += i;
});
}
});
println!("{}", total.into_inner().unwrap());
}This prints 10. Note these details:
totalis a plainMutex, not anArc<Mutex<_>>.let total = &total;makes a reference. Themoveclosure then copies the reference andiinto the thread. Without that line,movewould try to move the mutex itself into the first thread.- No
joincalls are needed. The scope joins the threads for you. - After the scope ends, no borrows remain.
total.into_inner()can take ownership of the mutex and return its value, wrapped in aResultbecause of poisoning.
Borrowing without a lock
Scoped threads also allow shared reads with no synchronization at all. Shared references (&T) are safe to use from many threads when T is Sync. You can also give each thread its own mutable slice with split_at_mut or chunks_mut. Then no Mutex is needed, because the borrow checker already proves the threads touch different data.
use std::thread;
fn main() {
let mut numbers = vec![1, 2, 3, 4, 5, 6];
thread::scope(|s| {
for chunk in numbers.chunks_mut(2) {
s.spawn(move || {
for n in chunk.iter_mut() {
*n *= 10;
}
});
}
});
println!("{:?}", numbers);
}This prints [10, 20, 30, 40, 50, 60].
Common errors
- Borrowing something that does not outlive the scope. A variable declared inside the scope closure cannot be borrowed by a thread, because it is dropped before the threads are joined. Declare the data before calling
thread::scope. - Forgetting
moveor the reference line. Withoutmove, a closure may borrow a loop variable likeithat does not live long enough. Withmoveand nolet total = &total;, the owned value is moved into the first iteration and the next one fails. - Panics. If a scoped thread panics and you did not join it yourself,
thread::scopepanics after all threads finish. Join the handle returned bys.spawnif you want to inspect the result.
When to choose scoped threads
| Situation | Choice |
|---|---|
| Threads must outlive the function that starts them | `Arc` with `thread::spawn` |
| Fork-and-join work on local data | `thread::scope` |
| Each thread works on its own part of a collection | `thread::scope` with `chunks_mut`, no lock |
Exercise
Why does the scoped-thread example compile with a Mutex borrowed from main, while the same code with thread::spawn does not?
Show answer
thread::spawn requires a 'static closure because the thread might outlive the function, so it cannot borrow local data. thread::scope joins every thread before it returns, so the borrowed Mutex is guaranteed to outlive them, and the compiler allows the borrow.