Cogs and Levers A blog full of technical stuff

rayon

Concurrency is about coordination. Parallelism is about throughput.

Rust gives you threads. Tokio gives you async tasks.

rayon gives you effortless data parallelism.

What Problem Does rayon Solve?

You have a large dataset. You want to process it across CPU cores. You do not want to manually manage threads.

rayon turns sequential iterators into parallel iterators.

Minimal Example

Cargo.toml

[dependencies]
rayon = "1"

main.rs

use rayon::prelude::*;

fn main() {
    let numbers: Vec<u64> = (0..1_000_000).collect();

    let sum: u64 = numbers
        .par_iter()
        .map(|n| n * 2)
        .sum();

    println!("sum = {sum}");
}

Change iter() to par_iter().

That’s it.

What’s Actually Happening?

Rayon:

  • Uses a work-stealing thread pool
  • Automatically balances work
  • Preserves iterator semantics

You write data transforms. Rayon handles scheduling.

Where It Fits

  • CPU-bound workloads
  • Image processing
  • Numeric computation
  • Batch processing

Not I/O-heavy tasks.

Should You Use It?

If you’re writing CPU-heavy code:

Yes.

Rayon is one of the cleanest concurrency abstractions in Rust.