liveBook · Manning

Rayon

As explained in Learn Rust in a Month of Lunches

Rayon is a Rust library for data-parallel programming that automatically distributes iterator-based work across threads.

Rayon is a Rust crate for speeding up iterator-heavy work. It automatically uses multiple threads, often requiring only a parallel version of an iterator method. section 17.4

Common sequential iterator methods have parallel Rayon counterparts:

  • Replace iter() with par_iter(). section 17.4
  • Replace iter_mut() with par_iter_mut(), into_iter() with par_into_iter(), and chars() with par_chars(). section 17.4
  • Import rayon::prelude::* to use these methods. section 17.4

Parallel vector update

Create a vector containing 2,000,000 zeros, then use par_iter_mut(), enumerate(), and for_each() to add each element's index plus one. The same computation can run faster on a machine with more available parallelism, but Rayon can also be slower for small or unsuitable workloads. section 17.4

use rayon::prelude::*;                                       #1
 
fn main() {
    let mut my_vec = vec![0; 2_000_000];
    my_vec
        .par_iter_mut()
        .enumerate()
        .for_each(|(index, number)| *number += index + 1);   #2
}

Shows the minimal change from sequential mutation to Rayon-backed parallel mutation. section 17.4

How Learn Rust in a Month of Lunches covers it

How deep it goes
Explains parallel iterator substitutions and benchmarks them, while deferring Rayon’s broader customization methods.
Examples
Uses a 2,000,000-element vector, indexed mutation, available parallelism, and repeated timing comparisons.
What it assumes
Assumes familiarity with Rust iterators and closures while building from familiar sequential iterator methods.
What you can do after
Apply it via Rayon by replacing supported iterator methods with parallel variants and comparing timing.
How it connects
Connects iterators, threads, mutable iteration, parallelism, and performance measurement.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.