typestar

rayon::join in Rust

join runs two closures that may go in parallel — the base of divide and conquer.

fn sum_slice(values: &[u64]) -> u64 {
    if values.len() <= 1_000 {
        return values.iter().sum();
    }
    let middle = values.len() / 2;
    let (left, right) = values.split_at(middle);
    let (a, b) = rayon::join(|| sum_slice(left), || sum_slice(right));
    a + b
}

fn main() {
    let values: Vec<u64> = (1..=100_000).collect();
    let total = sum_slice(&values);
    println!("{total}");
    assert_eq!(total, values.iter().sum::<u64>());
}

How it works

  1. Rayon decides whether a second thread is worth it.
  2. Recursive splitting is the natural fit for join.
  3. Below a threshold, do the work serially instead.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
408
Tokens
150
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 82 seconds.

Type this snippet

Step 1 of 3 in Splitting work, step 6 of 9 in Data parallelism with rayon.

← Previous Next →