Rust 标准库 1.63 增加了一个期待已久的功能:scoped thread(作用域线程)。
fn main() {
println!("Hello, world!");
use std::thread;
let vals = vec![
String::from("hi"),
String::from("from"),
String::from("the"),
String::from("thread"),
];
let v1 = &vals[0];
use crossbeam_channel::unbounded;
// Create a channel of unbounded capacity.
let (tx, rx) = unbounded::<&String>();
let mut a = vec![1, 2, 3];
let mut x = 0;
thread::scope(|s| {
s.spawn( || {
println!("hello from the first scoped thread");
// borrow `a` here
dbg!(&a);
for word in &vals {
tx.send(word);
}
});
s.spawn( || {
println!("hello from the second scoped thread");
// mutably borrow `x`, because no other threads are using it
x += a[0] + a[2];
for recv in rx {
println!("Got: {}", recv);
}
});
println!("hello from the main thread");
});
// after the scope, can modify and access the variables again
a.push(4);
assert_eq!(x, a.len());
}
【 在 z16166 的大作中提到: 】
: 给send()传递ref是不行的,因为这个ref是在发送线程(或者说负责发送的闭包)里的,
: 一旦发送线程结束(或者说发送的闭包销毁了),ref即失效,此后接收线程收到这个ref后就是dangling reference。
: 这样去掉for带来的问题后,也是报错:
: ...................
--
FROM 117.147.20.*