Future::spawn() 有点没用?我怎样才能多线程呢?
Future::spawn() kinda useless? How can I multi-thread this?
此处摘自 main
:
let value: Value = json::from_str(&sbuf).unwrap();
let coords = value.find("coordinates").unwrap().as_array().unwrap();
let x = Future::spawn(|| coords.iter().fold(0f64, |mut a,b| { a += read_coord_value(&b, "x"); a }));
let y = Future::spawn(|| coords.iter().fold(0f64, |mut a,b| { a += read_coord_value(&b, "y"); a }));
let z = Future::spawn(|| coords.iter().fold(0f64, |mut a,b| { a += read_coord_value(&b, "z"); a }));
println!("x: {}; y: {}; z: {}",
x.await().unwrap(),
y.await().unwrap(),
z.await().unwrap());
所以,基本上,我在这里所做的工作是行不通的,因为这个 spawn 调用要求传递给它的所有内容都具有静态生命周期——这意味着基本上没有任何工作是我可以避免重复的。完全没有。毫无意义。
什么是好的线程处理方法?
在这里,要正确地进行多线程处理,您需要使用作用域线程,std::thread::scoped(..)
。
这些线程不需要 'static
闭包来执行,但它们 必须 加入。
例如:
use std::thread::scoped;
fn main() {
let coords = [(1f64,2f64,3f64),(1.,2.,3.),(1.,2.,3.),(1.,2.,3.)];
let x = scoped(|| coords.iter().fold(0f64, |mut a,b| { a += b.0; a }));
let y = scoped(|| coords.iter().fold(0f64, |mut a,b| { a += b.1; a }));
let z = scoped(|| coords.iter().fold(0f64, |mut a,b| { a += b.2; a }));
println!("x: {}; y: {}; z: {}",
x.join(),
y.join(),
z.join());
}
此处摘自 main
:
let value: Value = json::from_str(&sbuf).unwrap();
let coords = value.find("coordinates").unwrap().as_array().unwrap();
let x = Future::spawn(|| coords.iter().fold(0f64, |mut a,b| { a += read_coord_value(&b, "x"); a }));
let y = Future::spawn(|| coords.iter().fold(0f64, |mut a,b| { a += read_coord_value(&b, "y"); a }));
let z = Future::spawn(|| coords.iter().fold(0f64, |mut a,b| { a += read_coord_value(&b, "z"); a }));
println!("x: {}; y: {}; z: {}",
x.await().unwrap(),
y.await().unwrap(),
z.await().unwrap());
所以,基本上,我在这里所做的工作是行不通的,因为这个 spawn 调用要求传递给它的所有内容都具有静态生命周期——这意味着基本上没有任何工作是我可以避免重复的。完全没有。毫无意义。
什么是好的线程处理方法?
在这里,要正确地进行多线程处理,您需要使用作用域线程,std::thread::scoped(..)
。
这些线程不需要 'static
闭包来执行,但它们 必须 加入。
例如:
use std::thread::scoped;
fn main() {
let coords = [(1f64,2f64,3f64),(1.,2.,3.),(1.,2.,3.),(1.,2.,3.)];
let x = scoped(|| coords.iter().fold(0f64, |mut a,b| { a += b.0; a }));
let y = scoped(|| coords.iter().fold(0f64, |mut a,b| { a += b.1; a }));
let z = scoped(|| coords.iter().fold(0f64, |mut a,b| { a += b.2; a }));
println!("x: {}; y: {}; z: {}",
x.join(),
y.join(),
z.join());
}