Rust 开发团队成员介绍了一项将在 Rust 1.63 标准库添加的重要新特性:scoped thread(作用域线程)。据介绍,这是系统层级的线程,与thread::spawn()
不同,scoped thread 支持线程使用局部变量,而不仅仅是静态变量。
官方示例:
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());
具体来说,传递给作用域的函数将提供一个Scope
对象,使用该对象可以通过 spawn 创建作用域线程。与非作用域线程不同,作用域线程支持非静态变量,因为作用域保证所有线程都将在作用域的末尾加入。在此函数返回之前,在作用域内生成的所有未手动加入的线程将自动加入。
详情查看文档。按照计划,Rust 1.63 将在 8 月 11 日发布。