Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Standard Library Modules

Rust thread::scope function

Reference for std::thread::scope: spawn threads that borrow local variables, how automatic joining works, panics, returning values and common patterns.

std::thread::scope runs a closure in which you can spawn threads that are guaranteed to finish before scope returns. Because of that guarantee, those threads may borrow variables from the surrounding function, something an ordinary thread::spawn forbids: it requires 'static data, so you would otherwise reach for Arc or clones.

The closure receives a &Scope. Calling s.spawn(...) on it starts a thread and returns a ScopedJoinHandle. When the closure ends, scope joins every thread that you did not join yourself, and only then returns.

Rust
let mut data = vec![1, 2, 3];
std::thread::scope(|s| {
    s.spawn(|| println!("len = {}", data.len()));
});
data.push(4);

Try it

Rust Borrowing local data in threads

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust Mutating disjoint parts and automatic joins

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Syntax

Rust
pub fn scope<'env, F, T>(f: F) -> T
where
    F: for<'scope> FnOnce(&'scope Scope<'scope, 'env>) -> T;

impl<'scope, 'env> Scope<'scope, 'env> {
    pub fn spawn<F, T>(&'scope self, f: F) -> ScopedJoinHandle<'scope, T>
    where
        F: FnOnce() -> T + Send + 'scope,
        T: Send + 'scope;
}
impl<'scope, T> ScopedJoinHandle<'scope, T> {
    pub fn join(self) -> Result<T, Box<dyn Any + Send + 'static>>;
    pub fn thread(&self) -> &Thread;
    pub fn is_finished(&self) -> bool;
}
Name Description
f The closure that spawns threads; its return value becomes the result of scope.
s.spawn(closure) Starts a thread whose closure may borrow anything that outlives the scope. The closure must be Send.
handle.join() Waits for one thread and returns its result, or the panic payload as Err.
Builder::spawn_scoped(s, f) Like spawn but lets you name the thread and set its stack size; returns io::Result.

Panics: if any scoped thread panics and you did not join it, scope itself panics after all threads have finished, with the message "a scoped thread panicked". If you joined the thread and handled the Err, scope does not panic.

Usage notes

  • A scoped closure can borrow shared data immutably from many threads at once, or one thread can hold a &mut to a given variable. The usual borrow rules still apply, and the compiler checks them.
  • To give each thread a different part of a mutable slice, split it first with chunks_mut, split_at_mut or iter_mut and move each piece into its closure.
  • Inside the spawned closure, move moves captured values (including references). Without it, variables are captured by reference, which is fine as long as they outlive the scope.
  • You do not need Arc for read-only data. You still need Mutex, atomics or channels when threads must change the same value.
  • Spawning is not free: each call creates an OS thread. For many small tasks, use a few threads that each process a slice, as in the examples.
  • Since a scope returns only after its threads finish, a thread that loops forever makes scope hang.
  • Stable since Rust 1.63. Before that, crates like crossbeam provided the same feature.