Concurrency Safety · 18 min · free with an account

Scoped Threads

Lesson preview · about 30%

Borrow local data while threads are guaranteed to join.

Core idea

thread::scope proves every spawned thread finishes before borrowed stack data disappears.

Start with the idea

thread::scope proves every spawned thread finishes before borrowed stack data disappears. It avoids unnecessary Arc or cloning when concurrency stays inside one lexical operation.

Ordinary thread::spawn may outlive the function that created it, so its closure generally needs owned, thread-safe data. thread::scope sets a tighter boundary: every scoped thread finishes before the scope returns. Within that boundary, a worker can borrow local values that remain alive until all workers join. This is useful for parallel processing of disjoint parts of a collection without cloning the entire collection into Arc.

The safety promise is about lifetime, not completion without failure. A scoped worker can still panic; the scope joins all its workers and can propagate an unhandled panic.

Keep learning, for free

The rest of this lesson is waiting for you.

Create a free account to read the complete explanation, see the infographic, explore the code, and try the exercises. All 742 lessons and algorithm steps are included.

No payment details. Your account opens the complete Academy.

← All lessons in Concurrency & Async