40. Scoped Threads — Borrow Across Threads Without Arc
Need to share stack data with spawned threads? std::thread::scope lets you borrow local variables across threads — no Arc, no .clone().
The problem
With std::thread::spawn, you can’t borrow local data because the thread might outlive the data:
| |
The classic workaround is wrapping everything in Arc:
| |
It works, but it’s noisy — especially when you just want to read some data in parallel.
The fix: std::thread::scope
Scoped threads guarantee that all spawned threads finish before the scope exits, so borrowing is safe:
| |
Mutable access works too
Since the scope enforces proper lifetimes, you can even have one thread mutably borrow something:
| |
Each thread gets exclusive access to its own element — the borrow checker is happy, no Mutex required.
When to reach for scoped threads
Use std::thread::scope when you need parallel work on local data and don’t want the overhead or ceremony of Arc/Mutex. It’s perfect for fork-join parallelism: spin up threads, borrow what you need, collect results when they’re done.