Sub topic 10
Borrowing local data with scoped threads
This chapter assumes you know ownership, borrowing, and lifetimes, closures and move, Result and unwrap, and how to run a program with cargo. You should also have read the earlier chapters on thread::spawn, join, and move closures.
The problem with spawn and borrowed data
thread::spawn requires its closure to be 'static. That bound means the closure may not hold references to anything that could be dropped before the thread ends. The compiler cannot know when a spawned thread will finish. The thread could outlive the function that created it, so the closure must own its data or borrow only data that lives for the whole program.
Here is code that looks harmless but does not compile:
use std::thread;
fn main() {
let numbers = vec![1, 2, 3];
let handle = thread::spawn(|| {
println!("{}", numbers.len());
});
handle.join().unwrap();
}The error says the closure may outlive numbers and suggests move. Adding move hands numbers to the thread. That works, but then main can no longer use the vector. If you need to keep using it, you have to clone it or wrap it in Arc. Both cost something and add code, even when you know the thread will finish before you touch the data again.
Scoped threads remove that restriction. std::thread::scope (stable since Rust 1.63) lets threads borrow local variables, because the scope itself guarantees that every thread inside it has finished before scope returns.
How thread::scope works
thread::scope takes a closure. That closure receives a reference to a Scope value, conventionally named s. You call s.spawn(...) on it instead of thread::spawn(...).
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. Three details matter here.
- The closures borrow
leftandrightdirectly. There is nomove, noArc, and no clone. s.spawnreturns aScopedJoinHandle. Callingjoinon it works like the ordinaryjoinand returns aResult.thread::scopereturns whatever the closure returns. Here that is a tuple of two sums.
Both threads read from the same vector at the same time. That is safe because shared references (&T) are Send when T is Sync, and Vec<i32> is Sync.
Why it is sound
The scope function does not return until all threads spawned in it have finished. The borrow checker uses this fact. The data you borrow must outlive the scope call, and the scope call outlives the threads. So no thread can observe a dangling reference.
The signature expresses this with two lifetimes, roughly 'scope for the lifetime of the scope and 'env for the lifetime of the borrowed environment, with 'env: 'scope. You rarely write these out, but they explain error messages. If you try to borrow a variable declared inside the scope closure and use it from a thread that outlives that closure body's locals, the compiler rejects it.
Automatic joining
You do not have to call join on scoped threads. When the scope closure ends, scope waits for every thread that has not yet been joined.
use std::thread;
fn main() {
let mut greeting = String::from("hello");
let words = ["alpha", "beta", "gamma"];
thread::scope(|s| {
for w in &words {
s.spawn(move || {
println!("{w}");
});
}
});
greeting.push_str(" world");
println!("{greeting}");
}The three lines from the threads can print in any order, but all of them appear before hello world. Note the move in this example. It moves the reference w (a &&str) into the closure, not the array. This is needed because w is a loop variable that dies at the end of each iteration, while the thread may still run. move copies the reference, which is Copy and points into words, which lives outside the scope.
The greeting variable is untouched by the threads, so it is usable afterward as normal. Once scope returns, all borrows taken inside it are over.
Mutable borrows in scoped threads
A scoped thread can also borrow mutably, as long as the usual aliasing rule holds: at any moment there is either one &mut or any number of &. The standard way to split work is to divide a slice into disjoint pieces.
use std::thread;
fn main() {
let mut data = vec![1, 2, 3, 4, 5, 6, 7, 8];
let (first, second) = data.split_at_mut(4);
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, 30, 40, 6, 7, 8, 9]. No lock is needed. The two threads hold &mut to different halves, so there is no sharing to protect. The type system proves the halves do not overlap, because split_at_mut returns two non-overlapping slices.
You cannot hand the same &mut to two threads. If both closures tried to capture &mut data, the compiler would report two mutable borrows at once. For overlapping access you still need Mutex or another synchronization tool, covered in the shared state chapter.
Chunks for many threads
When the number of pieces is not fixed, chunks_mut combined with a loop produces one disjoint slice per thread.
use std::thread;
fn main() {
let mut data: Vec<u32> = (1..=10).collect();
thread::scope(|s| {
for chunk in data.chunks_mut(3) {
s.spawn(move || {
for x in chunk.iter_mut() {
*x *= *x;
}
});
}
});
println!("{data:?}");
}This prints [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]. Each chunk is a &mut [u32]. A mutable reference is not Copy, so move transfers that one reference into its thread. This is exactly what you want, since each chunk belongs to exactly one thread.
Panics in scoped threads
Panic handling differs slightly from plain spawn. If you call join on a scoped handle, a panic comes back as an Err, as in the earlier panic chapter. If you do not join a thread and it panics, scope itself panics after all threads have finished, with a message saying a scoped thread panicked.
use std::thread;
fn main() {
let result = thread::scope(|s| {
let h = s.spawn(|| {
panic!("worker failed");
});
h.join().is_err()
});
println!("worker panicked: {result}");
}Because the code joins the handle itself and inspects the Err, the panic is handled and scope returns normally. The program prints worker panicked: true (plus the panic message on standard error). Remove the join and the whole scope call panics instead.
Scoped threads and channels
Channels combine well with scoped threads. The senders and receivers can live in the enclosing function, and no 'static bound applies to what the threads capture.
use std::sync::mpsc;
use std::thread;
fn main() {
let words = vec!["one", "two", "three"];
let (tx, rx) = mpsc::channel();
thread::scope(|s| {
for w in &words {
let tx = tx.clone();
s.spawn(move || {
tx.send(w.len()).unwrap();
});
}
drop(tx);
let mut lengths: Vec<usize> = rx.iter().collect();
lengths.sort();
println!("{lengths:?}");
});
println!("still have {} words", words.len());
}This prints [3, 3, 5] and then still have 3 words. The threads borrow words and still send results through a channel. The original tx is dropped inside the scope, so rx.iter() ends once every clone is gone. If you forgot that drop, the receiving loop would wait forever, the same failure described in the chapter on channel closing.
When to use scoped threads
| Situation | Better choice |
|---|---|
| Threads must outlive the function that starts them | `thread::spawn` with owned data or `Arc` |
| Work is split across threads and the function waits for all of it | `thread::scope` |
| Threads need to read or write a local buffer, then you use it afterward | `thread::scope` |
| A long-lived background service | `thread::spawn` |
| Many threads must mutate the same value | `Arc<Mutex<T>>`, with or without scope |
The rule of thumb: if the work is fork and join, where you start threads and wait for them all before continuing, scoped threads give simpler code with fewer clones. If the thread has its own lifetime, use spawn.
Common errors
- Borrowed value does not live long enough. You declared the variable inside the scope closure, but a thread tries to use it past that point, or you used plain
thread::spawninside a scope. Uses.spawn, and declare shared data before callingscope. - Cannot borrow as mutable more than once. Two closures capture the same
&mut. Split the data withsplit_at_mutorchunks_mut, or use aMutex. - Closure may outlive the current function in a loop. A loop variable is captured by reference. Add
moveso a copy of the reference goes into the thread. - Program hangs at the end of scope. A thread is blocked, often on
recvwith a live sender.scopewaits for every thread, so a blocked thread blocks the scope. Make sure all senders are dropped. - Unexpected panic from scope. A thread panicked and was never joined. Join the handle if you want to handle the failure yourself.
Exercises
Exercise
Why does thread::spawn(|| println!("{}", v.len())) fail to compile when v is a local Vec, while s.spawn(|| println!("{}", v.len())) inside thread::scope compiles?
Show answer
thread::spawn requires a 'static closure because the thread may outlive the function, so it cannot borrow v. thread::scope guarantees every scoped thread is finished before it returns, so the borrow of v cannot outlive v and the compiler accepts it.
Exercise
Two scoped threads need to modify the same Vec<i32>, one working on the first half and one on the second. How do you do it without a Mutex?
Show answer
Split the vector into disjoint mutable slices with split_at_mut (or chunks_mut), then give one slice to each thread. Because the slices do not overlap, the borrow checker allows two &mut borrows at once and no lock is needed.
Exercise
A scoped thread panics and you never call join on its handle. What does thread::scope do?
Show answer
It waits for all other threads to finish, then panics itself. To handle the failure instead, call join on the handle and check for an Err.