Sub topic 12
Scoped threads: borrowing without Arc
This chapter assumes you know thread::spawn, JoinHandle, move closures, and the Send and Sync rules from the earlier chapters. Here you will see how thread::scope lets threads borrow local data, and why the Send and Sync bounds still apply.
The problem with spawn
thread::spawn requires its closure to be 'static. The compiler cannot know when a spawned thread ends, so the thread must not hold references to anything on the caller's stack. The usual workaround is to move owned data into the thread, which means Arc for shared data and clones for each thread.
That works, but it costs an allocation, atomic reference counting, and extra code. Often you only want several threads to read a local Vec and finish before the function returns. In that case, the 'static requirement is stricter than the problem needs.
How thread::scope works
std::thread::scope (stable since Rust 1.63) creates a region of code in which threads are guaranteed to finish before the region ends. If the compiler can see that guarantee, the threads can borrow from the surrounding function.
use std::thread;
fn main() {
let data = vec![1, 2, 3];
let (sum, len) = thread::scope(|s| {
let a = s.spawn(|| data.iter().sum::<i32>());
let b = s.spawn(|| data.len());
(a.join().unwrap(), b.join().unwrap())
});
println!("sum = {}, len = {}", sum, len);
}This prints sum = 6, len = 3. Neither closure uses move, and nothing is wrapped in Arc. Both closures borrow data as &Vec<i32>.
The call has three parts:
thread::scoperuns your closure and passes it a handles, of type&Scope.s.spawnstarts a thread. It works likethread::spawn, but the closure may borrow data that outlives the scope.- When your closure returns,
scopejoins every thread you did not join yourself. Only then doesscopereturn.
The signatures
The simplified signature of Scope::spawn explains the rules:
// Simplified from the standard library
// pub fn spawn<F, T>(&'scope self, f: F) -> ScopedJoinHandle<'scope, T>
// where
// F: FnOnce() -> T + Send + 'scope,
// T: Send + 'scope,Compare this with thread::spawn, which needs F: Send + 'static and T: Send + 'static. The only change is that 'static becomes 'scope. Send is still required, and the borrow checker still applies.
Send and Sync still apply
A non-move closure that uses data captures &Vec<i32>. The closure is Send only if every captured value is Send. A shared reference &T is Send exactly when T is Sync. So borrowing across threads requires Sync, which is the relation from the earlier chapter that defines Sync through Send.
Vec<i32> is Sync, so the first example compiles. A type that is not Sync is rejected:
use std::rc::Rc;
use std::thread;
fn main() {
let data = Rc::new(5);
thread::scope(|s| {
s.spawn(|| println!("{}", data));
});
}This does not compile. The compiler reports that Rc<i32> cannot be shared between threads safely, because the closure captures &Rc<i32> and Rc<i32> is not Sync. Scoped threads remove the 'static requirement and nothing else. They do not make unsafe sharing legal.
| Requirement | `thread::spawn` | `Scope::spawn` |
|---|---|---|
| Closure is `Send` | yes | yes |
| Closure is `'static` | yes | no, only `'scope` |
| May borrow locals | no | yes |
| Needs `Arc` to share data | usually | usually not |
| Who joins the thread | you, or it detaches | you, or `scope` does it |
Sharing mutable state
Shared mutable state still needs a Sync primitive. The difference is that you can borrow the Mutex instead of wrapping it in Arc.
use std::sync::Mutex;
use std::thread;
fn main() {
let words = vec!["a", "bb", "ccc"];
let total = Mutex::new(0usize);
let total_ref = &total;
thread::scope(|s| {
for &w in &words {
s.spawn(move || {
*total_ref.lock().unwrap() += w.len();
});
}
});
println!("{}", total.into_inner().unwrap());
}This prints 6. Each closure is move, but what moves is a copy of the &Mutex<usize> reference and a copy of the &str. Both copies are cheap. The move keyword is needed here. Without it, the closure would borrow the loop variable w by reference, and w does not live as long as 'scope. Binding total_ref outside the loop is needed for the same reason: a move closure would otherwise try to move the Mutex itself.
After the scope ends, no thread holds a borrow. That is why total.into_inner() can take ownership of the Mutex again. With Arc, you would have to unwrap the Arc first.
Mutable borrows of disjoint data
Scoped threads can also hand out &mut references, as long as the borrow checker sees that they do not overlap. Methods such as chunks_mut and split_at_mut produce non-overlapping slices.
use std::thread;
fn main() {
let mut data = vec![1, 2, 3, 4, 5, 6];
thread::scope(|s| {
for chunk in data.chunks_mut(2) {
s.spawn(move || {
for x in chunk.iter_mut() {
*x *= 10;
}
});
}
});
println!("{:?}", data);
}This prints [10, 20, 30, 40, 50, 60]. No lock is needed because each thread has exclusive access to its own chunk. &mut [i32] is Send because [i32] is Send. The compiler proves there is no data race using ownership rules alone.
Edge cases
- Panics. If a scoped thread panics and you did not join it,
scopepanics after all threads have finished. If you calljoin()on the handle, you get theErrvalue instead, as withthread::spawn. - Borrow lifetimes. Threads can borrow data that was declared before the
scopecall. They cannot borrow variables declared inside the scope closure, because those do not outlive'scope. - Mutable conflicts. While threads borrow
datamutably, you cannot touchdatafrom the main thread inside the scope. After the scope ends, you can use it again. - Nested spawns. The handle
sis a shared reference and isCopy, so amoveclosure can capture it and calls.spawnagain. This lets a scoped thread start more scoped threads in the same scope. - Thread settings.
thread::Builder::spawn_scopedlets you set a thread name or stack size for a scoped thread. It returns anio::Resultbecause the operating system can refuse to create the thread. - Blocking.
scopeblocks the calling thread until every spawned thread is done. It is not a way to run background work and continue.
When to choose which
Use scoped threads when the work is bounded by one function call: parallel iteration over a slice, splitting a buffer, or running a few tasks over borrowed configuration. Use thread::spawn with Arc when a thread must outlive the function that started it, such as a background worker or a server loop.
Exercise
A scoped thread's closure borrows a Cell<i32> declared before the scope with s.spawn(|| c.set(1)). Does it compile? Explain using Send and Sync.
Show answer
It does not compile. The non-move closure captures &Cell<i32>. A &T is Send only when T is Sync, and Cell<i32> is Send but not Sync. The closure is therefore not Send, so Scope::spawn rejects it. Using Mutex<i32> or AtomicI32 fixes it, and you can still borrow either one without Arc.
Exercise
Why does the chunks_mut example need no Mutex, while two threads that both receive &mut data would not compile?
Show answer
chunks_mut returns non-overlapping &mut [i32] slices, so each thread has exclusive access to its own part of the vector. The borrow checker accepts this. Two &mut data borrows of the whole vector would overlap, and Rust allows only one mutable borrow of the same data at a time.
Exercise
What are the two bounds on the closure passed to Scope::spawn, and which bound from thread::spawn was relaxed?
Show answer
The closure must be FnOnce() -> T + Send + 'scope, and the result T must be Send + 'scope. The 'static bound from thread::spawn was relaxed to 'scope. Send is unchanged.