How to Use Scoped Threads in Rust (std

:thread::scope)

Use std::thread::scope to spawn threads that safely borrow local data and automatically join before the scope ends.

Use std::thread::scope to spawn threads that borrow data from the current stack frame without manual lifetime management. The scope ensures all spawned threads join before the function returns, allowing safe access to mutable references.

use std::thread;

fn main() {
    let mut data = vec![1, 2, 3];

    thread::scope(|s| {
        s.spawn(|| {
            println!("Thread 1: {}", data[0]);
        });
        s.spawn(|| {
            data.push(4);
        });
    });

    println!("Data after scope: {:?}", data);
}