Members of the Rust development team introduced an important new feature to be added to the Rust 1.63 standard library: scoped thread. This is described as a system-level thread, and unlike thread::spawn(), scoped thread supports the use of local variables by threads, not just static variables.

Rust development team

Official example.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
use std::thread;

let mut a = vec![1, 2, 3];
let mut x = 0;

thread::scope(|s| {
    s.spawn(|| {
        println!("hello from the first scoped thread");
        // We can borrow `a` here.
        dbg!(&a);
    });
    s.spawn(|| {
        println!("hello from the second scoped thread");
        // We can even mutably borrow `x` here,
        // because no other threads are using it.
        x += a[0] + a[2];
    });
    println!("hello from the main thread");
});

// After the scope, we can modify and access our variables again:
a.push(4);
assert_eq!(x, a.len());

Specifically, the function passed to the scope will provide a Scope object, which can be used to create a scoped thread via spawn to create a scoped thread. Unlike non-scoped threads, scoped threads support non-static variables because scopes guarantee that all threads will join at the end of the scope. All threads generated in the scope that are not manually joined will be joined automatically until this function returns.

see documentation for details. As planned, Rust 1.63 will be released on August 11.