Created
September 24, 2014 18:22
-
-
Save saosebastiao/67dcf4ea695338270936 to your computer and use it in GitHub Desktop.
How would I parallelize this?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::io::timer; | |
use std::time::Duration; | |
use std::sync::Future; | |
trait Constraint { | |
fn is_satisfied(&self) -> bool; | |
} | |
#[deriving(Send)] | |
struct Foo { name: &'static str, a: bool, b: bool } | |
#[deriving(Send)] | |
struct Bar { name: &'static str, a: bool } | |
impl Constraint for Foo { | |
fn is_satisfied(&self) -> bool { | |
let res = self.a && self.b; | |
timer::sleep(Duration::seconds(2)); | |
println!("{} is {}",self.name,res); | |
res | |
} | |
} | |
impl Constraint for Bar { | |
fn is_satisfied(&self) -> bool { | |
let res = self.a; | |
println!("{} is {}",self.name,res); | |
res | |
} | |
} | |
fn main(){ | |
let mut cs: Vec<Box<Constraint>> = Vec::with_capacity(10); | |
cs.push(box Foo {name: "c1",a: true,b: true} as Box<Constraint>); | |
cs.push(box Foo {name: "c2",a: true,b: true} as Box<Constraint>); | |
cs.push(box Foo {name: "c3",a: true,b: true} as Box<Constraint>); | |
cs.push(box Bar {name: "c4",a: true} as Box<Constraint>); | |
cs.push(box Bar {name: "c5",a: false} as Box<Constraint>); | |
cs.push(box Foo {name: "c6",a: true,b: true} as Box<Constraint>); | |
cs.push(box Foo {name: "c7",a: true,b: true} as Box<Constraint>); | |
cs.push(box Bar {name: "c8",a: true} as Box<Constraint>); | |
cs.push(box Bar {name: "c9",a: true} as Box<Constraint>); | |
cs.push(box Foo {name: "c10",a: true,b: true} as Box<Constraint>); | |
let slow_serial = cs.iter().all(|x| x.is_satisfied()); | |
// following does not work | |
// error: cannot capture variable of type `&Box<Constraint:'static+Send>`, which does not fulfill `'static+Send`, in a bounded closure | |
// let slow_parallel_tasks = cs.iter().map(|x| Future::spawn(proc() { x.is_satisfied() })); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment