Reputation:
Excerpt from main
here:
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());
So, basically, what I'm doing here won't work because this spawn call requires everything that is passed to it to have a static lifetime--which means that there is basically no work I can avoid repeating. At all. Pointless.
What's a good way to do threading here?
Upvotes: 1
Views: 125
Reputation: 15002
Here, to properly do a multithreading, you need to used scoped threads, with std::thread::scoped(..)
.
These threads do not need a 'static
closure to execute, but they must be joined.
For example:
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());
}
Upvotes: 2