0PricingLogin
Learn Rust Coding · Lesson

Scoped Threads

Borrow across threads.

The Problem with Borrowing in Threads

A normal thread::spawn closure must be 'static: it cannot borrow local variables, because the thread might outlive the function that owns them. That is why you so often see move and Arc.

Scoped threads solve this by guaranteeing every thread finishes before the scope ends, so borrowing local data becomes safe.

Why spawn Needs 'static

With thread::spawn, the spawned thread can keep running after main or any function returns. If it borrowed a local variable, that variable could be destroyed while the thread still used it. Rust forbids this at compile time, forcing you to move owned data into the closure.

use std::thread;

fn main() {
    let nums = vec![1, 2, 3];
    // move transfers ownership into the thread
    let handle = thread::spawn(move || {
        println!("in thread: {:?}", nums);
    });
    handle.join().unwrap();
}

All lessons in this course

  1. mpsc Channels
  2. Sharing State with Arc/Mutex
  3. Scoped Threads
  4. Crossbeam Channels
← Back to Learn Rust Coding