Skip to content

Rayon

Terminal window
cargo add rayon

You can also configure the threadpool for Rayon, though I wouldn’t recommend it, you’ll most likely make it better on your machine and worse for everyone else.

.setup(|app| {
rayon::ThreadPoolBuilder::default().build_global().unwrap();
})

Instead of using boring old synchronous iterators, lets make them parallel with Rayon. Just replace .iter() with par_iter() and presto, your synchronous task is now fully parallel.

use rayon::prelude::*;
fn sum(inputs: Vec<i32>) -> i32 {
inputs.par_iter()
.map(|&i| i * i)
.sum()
}
fn main() {
println!("{}", sum(vec![1,2,3,4,5]));
}

If you don’t want to make use of the global threadpool you can make a temporary local threadpool for use in a specific task.

let pool = rayon::ThreadPoolBuilder::default().build().unwrap();
let do_it = || {
print!("one ");
pool.install(||{});
print!("two ");
};
rayon::join(|| do_it(), || do_it());

References