Sub topic 12
Scoped threads: borrowing without Arc
This chapter assumes you know thread::spawn, move closures, and the Send and Sync rules from the earlier chapters. This chapter shows how thread::scope lets threads borrow local data, so you can skip Arc.
Why spawn forces you to move or share ownership
thread::spawn requires the closure to be 'static. The compiler cannot know when a spawned thread ends, so the closure may not borrow from the caller's stack. This code fails:
use std::thread;
fn main() {
let data = vec![1, 2, 3];
let handle = thread::spawn(|| {
println!("{:?}", data);
});
handle.join().unwrap();
}The error says the closure "may outlive the current function, but it borrows data". The usual fix is Arc, or move plus a clone. Both add allocation and reference counting you may not need.
thread::scope
std::thread::scope (stable since Rust 1.63) creates a scope. Every thread spawned inside it is joined automatically before scope returns. Because the threads cannot outlive the scope, the 'static bound is replaced by a lifetime tied to the scope. The closures can then borrow locals directly.
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. Both threads hold a &Vec<i32>. Sharing that reference across threads is allowed because Vec<i32> is Sync, and &T is Send exactly when T is Sync.
Mutable borrows
Scoped threads can also take &mut borrows, as long as the borrows do not overlap. Splitting a slice into disjoint chunks gives each thread exclusive access to its own part:
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]. Each closure moves its own &mut [i32]. A &mut T is Send when T is Send, so no lock is needed. The borrow checker proves the chunks are disjoint.
What still applies
Scoped threads remove the 'static requirement. They do not remove Send. The closure passed to s.spawn must still be Send, and Send and Sync still decide what it may capture.
- A shared borrow
&TneedsT: Sync. - A mutable borrow
&mut TneedsT: Send. - Moved values need to be
Send.
When to choose which
| Situation | Use |
|---|---|
| Work finishes before the function returns | `thread::scope` |
| Thread must outlive the caller, such as a background worker | `thread::spawn` with `Arc` or owned data |
If a spawned thread panics and you never join it, scope still joins it and then panics itself, so failures are not lost.
Exercise
Inside thread::scope, you capture an Rc<i32> by reference in a spawned closure. The 'static bound no longer applies, so why does the code still fail to compile?
Show answer
The closure must still be Send. Capturing &Rc<i32> makes the closure Send only if Rc<i32> is Sync. Rc is not Sync because its reference count is not atomic, so the compiler rejects it. Using Arc<i32>, or borrowing a plain i32 directly, fixes it.