Sub topic 13
Scoped threads: sharing without Arc
This chapter assumes you know thread::spawn, JoinHandle, move closures, and the basics of Arc<Mutex<T>> from the earlier chapters. It also assumes you can read Rust borrow checker errors.
Why `thread::spawn` forces Arc
thread::spawn requires its closure to be 'static. The compiler cannot know when a spawned thread ends, so the closure may not borrow anything from the calling function. Anything the thread uses must be owned by the closure or live for the whole program.
This is why you cloned an Arc for every thread in the earlier chapters. Arc makes the data owned, and reference counting decides when it is freed.
The following code does not compile:
use std::thread;
fn main() {
let numbers = vec![1, 2, 3];
// Does not compile: closure may outlive the current function,
// but it borrows `numbers` (error E0373).
let handle = thread::spawn(|| {
println!("{:?}", numbers);
});
handle.join().unwrap();
}You call join a few lines later, but the compiler does not use that fact. The signature of spawn only promises that the thread may run for any length of time.
How `thread::scope` changes the rule
std::thread::scope, stable since Rust 1.63, gives the compiler the guarantee it was missing. You call it with a closure, and that closure receives a scope handle s. Threads started with s.spawn(...) are guaranteed to finish before thread::scope returns. Because they cannot outlive the scope, they may borrow any local variable that lives longer than the scope.
Here is the earlier failing example, fixed with a 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. Three things differ from the spawn version:
- The closures borrow
leftandright. There is nomoveand no clone. s.spawnreturns aScopedJoinHandle. Callingjoinon it returns the closure's result, just like a normalJoinHandle.- The value of the scope closure becomes the value of
thread::scope. Here that is a tuple of results.
The closure passed to s.spawn can also take the scope handle as an argument, as in s.spawn(|_| ...), in older crates such as crossbeam. The standard library version takes a closure with no arguments, as shown above.
Mutating shared data without Arc
When threads need to modify the same value, you still need synchronization. Scoped threads only remove the ownership requirement. A Mutex can now be borrowed directly:
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. Compare it with the Arc<Mutex<T>> version:
- There is no
Arc::newand noArc::clone, so there is no atomic reference counting. - Each thread receives a plain
&Mutex<i32>. - The line
let total = &total;creates a reference thatmovecan copy into each closure. Without it,movewould try to move the wholeMutexinto the first thread, and the second iteration would fail to compile. - After the scope ends, no borrow remains.
total.into_inner()consumes the mutex and returnsLockResult<i32>, and you can do that without anyArc::try_unwrapstep.
The last point is a practical gain. With Arc, getting the value back out requires either locking one last time or Arc::try_unwrap, which fails if another clone still exists. With scoped threads, the compiler already knows all borrowers are gone.
Often you do not need a lock at all
A scope also makes it easy to give each thread exclusive access to a different part of the data. Shared references are not needed, so neither is a Mutex:
use std::thread;
fn main() {
let mut data = vec![1, 2, 3, 4, 5, 6, 7, 8];
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, 70, 80]. chunks_mut hands out non-overlapping &mut [i32] slices. The borrow checker accepts that each one goes to a different thread, because none of them overlap. Each thread works without locking, and there is no contention. After the scope, data is fully usable again.
This is the best case for scoped threads. When the work divides cleanly, the borrow checker proves safety at compile time and you pay no runtime cost.
What the compiler still checks
Scoped threads relax the lifetime requirement, not the thread-safety rules. Send and Sync still apply:
| Closure captures | Allowed in a scoped thread? | Reason |
|---|---|---|
| `&Vec<i32>` | Yes | `Vec<i32>` is `Sync`, so `&Vec<i32>` is `Send` |
| `&Mutex<i32>` | Yes | `Mutex<T>` is `Sync` when `T` is `Send` |
| `&mut [i32]` (disjoint slice) | Yes | `&mut T` is `Send` when `T` is `Send` |
| `&Rc<i32>` | No | `Rc` is not `Sync`, so a reference to it is not `Send` |
| `&Cell<i32>` | No | `Cell` is not `Sync` |
| `&mut` to the same variable in two threads | No | Two live mutable borrows of one place |
So the compiler still rejects shared non-thread-safe types. Your design problem is the same: if two threads touch the same data and at least one writes, you need a Mutex, RwLock, or atomic. The scope only decides how the reference reaches the thread.
Panics and the scope
If a scoped thread panics and you did not join it yourself, thread::scope waits for every thread to finish and then panics itself with the message a scoped thread panicked. You cannot silently lose a failure by forgetting a handle.
If you do call join on a handle, you receive the Err from that thread, as with normal threads, and the scope does not panic for it. This gives you a choice:
- Ignore the handles for fail-fast behavior. Any worker panic propagates to the caller.
- Join each handle and handle the
Erryourself when you want to collect partial results.
The same Mutex poisoning rules from the earlier chapter apply. A scoped thread that panics while holding a guard poisons the mutex, and the final into_inner().unwrap() in the total example would then return an error. If the scope itself panics first, your code after the scope never runs.
Limits and when to choose something else
Scoped threads suit a fork-join shape: start workers, wait for all of them, continue. They fit poorly in these cases:
- Threads that must outlive the function. A background worker that keeps running after you return needs
thread::spawn, owned data, and usuallyArc. - Long-lived services. A scope blocks its caller until every thread is done, so a server loop inside a scope would hold the caller forever.
- Detached tasks. Everything in a scope is joined, so there is no fire-and-forget.
- Return before completion. The calling thread cannot do other work while the scope runs, unless it does that work inside the scope closure itself. You can do this. Code in the scope closure after your
s.spawncalls runs concurrently with the spawned threads.
Two minor notes. First, scoped spawning can fail to compile with confusing lifetime errors if a closure captures a variable declared inside the scope closure. Spawned closures can borrow only things declared before the call to thread::scope, or things that live longer than the scope. Second, spawning threads costs the same either way. The saving over Arc is the clone and the atomic count, which is small next to thread creation. Choose scoped threads for the clarity and the compile-time guarantees, not for speed.
Exercise
You write a scoped thread that increments a plain i32 counter declared before thread::scope, using s.spawn(|| counter += 1) in a loop of four iterations. It does not compile. Name the reason, and give two different fixes that keep scoped threads.
Show answer
Each iteration creates a closure holding a mutable borrow of the same counter, and the borrow checker rejects more than one live &mut to it at once, which would also be a data race. Fix 1: make the counter a Mutex<i32> (or AtomicI32), borrow it as &counter in each thread, and increment through lock() or fetch_add. Fix 2: remove the sharing by giving each thread its own result. Return a value from each ScopedJoinHandle and sum the results after joining, or give each thread a disjoint &mut slice with chunks_mut.