Concurrency Safety · 18 min · free lesson

Scoped Threads

Borrow local data while threads are guaranteed to join.

Core idea

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

Diagram for Scoped Threads: a Rust code example flows to the lesson rule and the key observation.
Every scoped thread finishes before scope returns, so borrowing values is allowed.

Understand it

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. Write the error policy explicitly if a worker result matters. Also avoid making the borrow invalid yourself: if one worker reads a value, the usual borrowing rules still prevent an overlapping mutable borrow of that same value. A scope is no shortcut around aliasing or synchronization.

Try dividing a slice into two non-overlapping mutable halves with split_at_mut, then process one half in each scoped worker. Predict why the compiler accepts those two borrows. Change the code so both workers try to mutate the entire slice and read the rejection. Finally compare the scoped form with an owned Vec moved into an ordinary spawned thread. Use the scope when the work naturally ends inside the current operation; use detached or longer-lived tasks only when you have an explicit ownership and shutdown plan.

Read the code

let values = [2, 4, 6];
std::thread::scope(|scope| {
    scope.spawn(|| {
        println!("{}", values.len());
    });
});

Every scoped thread finishes before scope returns, so borrowing values is allowed.

Practice starter

let mut values = [2, 4, 6, 8];
let (left, right) = values.split_at_mut(2);
std::thread::scope(|scope| {
    scope.spawn(|| left[0] += 1);
    scope.spawn(|| right[0] += 1);
});
println!("{values:?}");

Practise this code in Playground ↗

Try it

Predict what this prints. Then make both workers change values directly instead of one half each, and read the rejection.

What success looks like: You can say why two disjoint &mut halves compile and why two mutable borrows of values do not.

Check your understanding

Why may these threads borrow from values?

Reveal the answer
  1. The scope joins them before values can go away
  2. Arrays are stored in static memory
  3. spawn copies the whole array

thread::scope joins every thread before it returns, so a borrow of values cannot outlive the array. split_at_mut keeps the two mutable borrows disjoint.

Go deeper

Common misconception: “A thread can never borrow a local variable, so the data must go in an Arc.”

thread::scope proves every spawned thread finishes before borrowed stack data disappears, so a scoped thread may borrow locals with no Arc or clone.

  1. Open the scope: std::thread::scope runs its closure and passes it scope, the handle that starts threads tied to this call.
  2. Borrow in the worker: The spawned closure reads values through a shared borrow, with no move, so values stays usable by main.
  3. Reach the join: The scope waits for the worker before returning, so 3 has printed by the time the line after the scope runs.

Transfer challenge: Replace scope.spawn with std::thread::spawn in the example and predict the compiler error. Then add move and explain why values is still usable afterwards.

Connections

  • Async Patterns: join, select, and cancellation
  • Mutex Poisoning: Notice a panic that may leave state inconsistent
Learn this lesson with AI

Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.

I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools.
Lesson: Scoped Threads (courseId "concurrency", lessonId "scoped-threads")
Link: https://crabrix.com/learn/concurrency/scoped-threads/
Goal: thread::scope proves every spawned thread finishes before borrowed stack data disappears.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=concurrency/scoped-threads) and I will write the code there.
Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.

In Claude Code, Codex or Cursor, paste it into a chat with Crabrix Academy connected. On a phone, the Claude and ChatGPT apps open the same links.