Hi,
In the following code, I would make evaluate_solution() in main() function run in parallel mode using rayon crate. But, the code doesn't work. How can I do that ?
extern crate rayon;
use rayon::prelude::*;
pub trait Mytrait {
fn testfn(&mut self, solution : &Vec<f64>)-> f64 {
solution.iter().fold(0.0f64, |sum, x| sum +x)
}
}
pub struct Solution{
value: f64,
data : Vec<f64>,
problem : Box<dyn Mytrait + 'static>,
}
impl Solution {
pub fn new(gens : Vec<f64>, problem :Box<dyn Mytrait+ 'static>)->Solution {
Solution {
values: 0.0f64,
data : gens,
problem : problem,
}
}
pub fn evaluate_solution(&mut self){
self.values=self.problem.testfn(&self.data);
}
}
#[derive(Debug, Clone)]
pub struct Problem{
state : bool,
}
impl Mytrait for Problem {
fn testfn(&mut self, solution : &Vec<f64>) -> f64 {
self.state = true;
let prod = solution.iter().fold(0.0f64, |sum, x| sum * x);
prod
}
}
fn main() {
let mut p = Problem{
state : false,
};
//Initialization
let mut list = initialize(&mut p);
//Parallel evaluation
list.par_iter_mut().for_each(|s|
s.evaluate_solution()
);
for g in list.iter(){
println!("value: {}", g.values);
}
}
fn initialize<T: Mytrait + Clone + 'static>(problem : &mut T)->Vec<Solution>{
//initialize default data
let mut data =Vec::new();
for j in 0..100{
data.push(j as f64);
}
let mut list = Vec::new();
for _i in 0..10{
//make new copy of problem
let nwp = problem.clone();
let g = Solution::new(data.clone(), Box::new(nwp));
list.push(g);
};
list
}