Sub topic 10
Borrowing local data with scoped threads
This chapter assumes you know ownership and borrowing, closures and move, thread::spawn and join, and Result with unwrap. Scoped threads solve one specific problem: letting a thread borrow local data without Arc or cloning.
The problem with plain spawn
thread::spawn requires its closure to be 'static. The compiler cannot know when a spawned thread will finish, so the closure may not hold references to local variables. The function that owns those variables might return first, leaving the thread with dangling references.
use std::thread;
fn main() {
let numbers = vec![1, 2, 3];
let handle = thread::spawn(|| {
println!("{}", numbers.len());
});
handle.join().unwrap();
}This fails with an error saying the closure may outlive the current function, because it borrows numbers. Adding move fixes the error, but the thread then owns numbers, and main can no longer use it. The usual workaround is to wrap the data in Arc or clone it.
How thread::scope works
std::thread::scope creates a scope. Threads started with s.spawn inside it are guaranteed to finish before scope returns. If you do not join one yourself, the scope joins it automatically at the end. Because the compiler knows the threads cannot outlive the scope, they may borrow anything that outlives the scope.
use std::thread;
fn main() {
let numbers = vec![1, 2, 3, 4, 5, 6];
let (left, right) = numbers.split_at(3);
let (a, b) = thread::scope(|s| {
let h1 = s.spawn(|| left.iter().sum::<i32>());
let h2 = s.spawn(|| right.iter().sum::<i32>());
(h1.join().unwrap(), h2.join().unwrap())
});
println!("{a} {b}");
}This prints 6 15. Both closures borrow slices of numbers, with no move, no Arc, and no clone. After the scope ends, numbers is still usable in main.
The closure passed to scope receives a scope handle, here named s. You call s.spawn on it instead of thread::spawn. Each s.spawn returns a handle with join, and join returns a Result just as it does for ordinary threads. The value returned by the scope closure becomes the value of thread::scope(...).
Borrowing rules still apply
Scoped threads do not relax the borrow checker. They only remove the 'static requirement. Several threads may hold shared references (&) to the same data at once. Only one may hold a mutable reference (&mut), and not alongside any shared reference.
This example gives each thread its own mutable slice, so the borrows do not overlap.
use std::thread;
fn main() {
let mut data = vec![1, 2, 3, 4];
let (first, second) = data.split_at_mut(2);
thread::scope(|s| {
s.spawn(|| {
for x in first.iter_mut() {
*x *= 10;
}
});
s.spawn(|| {
for x in second.iter_mut() {
*x += 1;
}
});
});
println!("{data:?}");
}This prints [10, 20, 4, 5]. The threads are not joined by hand, because the scope waits for them. Once the scope ends, the mutable borrows end too, so data can be printed.
The Send and Sync rules from earlier still apply. Sharing &T across threads requires T: Sync, and moving a &mut T to another thread requires T: Send.
Panics in scoped threads
If a scoped thread panics and you did not join it, thread::scope panics after all threads have finished. If you call join yourself, you get an Err as usual and can handle it.
When to use which
| Situation | Choice |
|---|---|
| Threads must outlive the function that starts them | `thread::spawn` with `move`, `Arc`, or channels |
| Threads finish before the function returns, and data is local | `thread::scope` |
| Splitting one slice or collection into parts for parallel work | `thread::scope` |
Exercise
Why does thread::spawn(|| println!("{}", v.len())) fail to compile when v is a local Vec, while the same closure inside s.spawn within thread::scope compiles?
Show answer
thread::spawn requires a 'static closure because the thread might outlive the function that owns v, so borrowing v is rejected. thread::scope guarantees every thread spawned in it finishes before the scope returns, so the borrow of v cannot dangle and the compiler accepts it.
Exercise
In the mutable slices example, what would happen if both threads tried to mutate data directly through separate &mut data borrows?
Show answer
The code would not compile. Two mutable borrows of the same value cannot exist at once, even in scoped threads. Splitting the data with split_at_mut gives each thread a non-overlapping &mut slice, which the borrow checker accepts.