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
- Rayon decides whether a second thread is worth it.
- Recursive splitting is the natural fit for
join. - Below a threshold, do the work serially instead.
Keywords and builtins used here
Vecfnifletmainreturnsum_sliceu64
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.
Step 1 of 3 in Splitting work, step 6 of 9 in Data parallelism with rayon.