We use cookies to understand how the site is used and to display ads. Analytics and advertising only run after you accept. You can change your choice anytime. Privacy policy

Skip to content
devvkit
$devvkit learn --librarie rayon-guide

Rayon Guide

[rust][parallel][concurrency]
Rust
Install
cargo add rayon

Rayon converts sequential iterators to parallel with a single method call: par_iter().

Work-stealing scheduler dynamically balances work across threads without global locking.

Rayon guarantees thread-safety: the compiler ensures your closure is Send + Sync.

Setup

Add dependency· Cargo.toml.
cargo add rayon

Parallel Iterators

Basic par_iter· Parallel map.
use rayon::prelude::*;

let numbers: Vec<i32> = (0..100_000).collect();
let doubled: Vec<i32> = numbers.par_iter().map(|n| n * 2).collect();
Parallel filter/map· Chain parallel ops.
let evens: Vec<_> = (0..1000).into_par_iter()
    .filter(|n| n % 2 == 0)
    .map(|n| n * n)
    .collect();
Parallel sum· Reduce in parallel.
let sum: i32 = (0..1_000_000).into_par_iter().sum();
let max = (0..1_000_000).into_par_iter().max();
Parallel sort· Multi-threaded sort.
let mut vec: Vec<i32> = /* ... */;
vec.par_sort();  // parallel quicksort
Find any· Short-circuit search.
let found = data.par_iter().find_any(|&&x| x == 42);

Custom Operations

Fork-join· Manual parallelism.
use rayon::join;

let (left, right) = join(
    || process_half(&data[..mid]),
    || process_half(&data[mid..]),
);

Performance

Custom thread pool· Control parallelism.
use rayon::ThreadPoolBuilder;

let pool = ThreadPoolBuilder::new()
    .num_threads(4)
    .build()
    .unwrap();

pool.install(|| {
    data.par_iter().for_each(|item| process(item));
});