skip to content

With Rayon in Rust, which results keep sequential order across `collect`, `for_each`, `reduce` and `sum`, and what must a `reduce` operation satisfy?

level: middleimportance: should knowfreq 35%

answer

  1. results versus side effects
  2. collect stitches pieces back in place
  3. identity is a closure called often
  4. floats break associativity

basics

~20 s

Rayon's collect into a Vec keeps input order, but for_each side effects run in any order. reduce and sum combine pieces in an unspecified grouping, so the operation must be associative and the identity closure a true identity.

solid answer

~40 s

Rayon promises that parallel iterators produce the same results as sequential ones, but not the same order of side effects. `collect()` into a `Vec` reassembles pieces in position order, even through `filter`; `for_each` runs its closure on whichever worker reaches an item, so printing or sending happens in any order. `reduce(identity, op)` calls `identity` as often as it likes to seed each piece and applies `op` in an unspecified grouping, so `op` must be associative and `identity()` a true identity, or the result is non-deterministic. Integer `sum` is deterministic; an `f32` sum can differ in its last bits from the sequential loop. For searches, `find_first` keeps sequential semantics and `find_any` returns any match.

code

rust · 20 lines
rust
use rayon::prelude::*;

fn main() {
    let ids: Vec<u32> = (0..20).collect();

    // map + filter + collect into Vec: same order as the sequential chain
    let even_sq: Vec<u32> = ids.par_iter().filter(|&&x| x % 2 == 0).map(|&x| x * x).collect();
    let seq: Vec<u32> = ids.iter().filter(|&&x| x % 2 == 0).map(|&x| x * x).collect();
    assert_eq!(even_sq, seq);

    // for_each: side effects run in whatever order the workers reach them
    ids.par_iter().for_each(|x| print!("{x} "));
    println!();

    // f32 sum: the grouping of + is unspecified, so the bits may differ from a sequential sum
    let xs: Vec<f32> = (1..=1_000_000).map(|i| 1.0 / i as f32).collect();
    let par: f32 = xs.par_iter().sum();
    let seq: f32 = xs.iter().sum();
    println!("par {par} seq {seq} equal {}", par == seq);
}

go deeper

for a junior

Recall that collect keeps the input order while for_each side effects may run in any order.

for a middle

Explain why reduce needs an associative op and a true identity closure, and why a parallel float sum can differ from the sequential one.

for a senior

Port a sequential chain safely: collect before ordered side effects, choose find_first or find_any deliberately, and keep bit-exact numeric code off parallel float reductions.

for a principal

Decide where reproducibility matters, such as golden tests, financial totals or simulations, and make the team rule explicit rather than discovering it through flaky tests.

## Results versus side effects Rayon's README makes a specific promise: parallel iterators produce, for the most part, **the same results as their sequential counterparts**. The caveat it names is **side effects** (sending on a channel, writing to disk, printing), which may happen in a different order. Knowing exactly where that line falls is what lets you parallelise a chain without changing its output. **Results keep their order.** A chain that ends in `collect()` into a `Vec`, or `collect_into_vec`, produces elements in the original order, even through `filter`, `map` and `flat_map`. Rayon splits the input into pieces, processes them on different workers and stitches the pieces back together in position order. The example asserts that a parallel `filter` + `map` + `collect` equals the sequential one. The same holds for other ordered targets: collecting `String` pieces into a `String` concatenates them in input order, so uppercasing eight words in parallel still yields them in their original sequence. **Side effects do not.** `for_each`, `for_each_with` and `inspect` run the closure on whichever worker reaches an item first. Two runs of the same program print the numbers 0 to 19 in two different orders. If order matters, compute values in parallel, `collect` them, then perform the effects sequentially. ## `reduce`, `sum` and associativity Reductions combine all items into one value. Rayon's ```rust fn reduce<OP, ID>(self, identity: ID, op: OP) -> Self::Item where OP: Fn(Self::Item, Self::Item) -> Self::Item + Sync + Send, ID: Fn() -> Self::Item + Sync + Send, ``` differs from a sequential `fold` in two ways that its documentation spells out: 1. **`identity` is a closure, not a value.** Rayon may call it many times, inserting an identity at the start of each piece so pieces can be reduced independently. It must produce a **true identity**: zero for addition, an empty map for merging maps. 2. **The order in which `op` is applied is not fully specified.** The grouping varies with how the work was split, so `op` should be **associative** (`(a op b) op c == a op (b op c)`) or the result will be non-deterministic. `sum()` and `product()` carry the same note. Integer addition is associative, so an integer `sum` that does not overflow is deterministic. **Floating-point addition is not**: rounding depends on grouping, so a parallel `f32` sum of a million reciprocals printed `14.392728` while the sequential loop printed `14.357358`. Neither is wrong; they are different roundings. Code that needs bit-identical floating-point results (reproducible simulations, golden-file tests) must not depend on a parallel float reduction. `reduce_with(op)` needs no identity and returns `Option`, `None` for an empty iterator; the documentation calls it simpler but somewhat less efficient than `reduce`. `fold(identity, op)` is the parallel-only middle step: it produces **one partial result per piece**, which you then combine with `reduce` or `sum`. ## Searching: first versus any The same distinction applies to searches: | Method | Returns | Order guarantee | |---|---|---| | `find_first(p)` | the sequentially first match | yes; work to the right of a match stops | | `find_last(p)` | the sequentially last match | yes; work to the left of a match stops | | `find_any(p)` | whichever match a worker finds first | none; fastest | | `position_first` / `position_any` | index of a match | same split as above | `any` and `all` short-circuit and are deterministic because their answer is a single boolean. ## Where order is not defined at all Some sources have no useful order to begin with. A parallel iterator over a `HashMap` has no order, like sequential iteration over it. `par_bridge()`, which turns any sequential `Iterator` (a channel receiver, lines from a reader) into a parallel one by pulling items one at a time, is documented as **not guaranteed to keep the order** of the original iterator. Collecting from it and then sorting, as its own documentation example does, is the honest way to get a stable result. ## A checklist for porting a chain - Ends in `collect`, `count`, `any`, `all`, integer `sum` or `max`: output unchanged. - Ends in `for_each` with side effects: order changes; collect first if order matters. - Uses `reduce` or `fold`: check that the operation is associative and the identity closure is a true identity. - Sums or multiplies floats: expect run-to-run differences in the last bits. - Uses `find`-style searches: pick `find_first` for sequential semantics, `find_any` for speed.

  • Why does Rayon's `reduce` take `identity` as a closure rather than a single value?
    Rayon splits the input into pieces reduced independently and may seed each piece with its own identity, so it needs to produce a fresh identity many times, possibly on different threads. A closure bounded `Fn() -> Item + Sync + Send` can do that for any item type, including non-`Copy` ones such as an empty `HashMap`. If identity is not a true identity, each extra seed corrupts the result.
  • A test compares a parallel `f64` sum with a stored golden value and fails intermittently. What do you change?
    Floating-point addition is not associative, and Rayon's `sum` applies `+` in an unspecified grouping, so the last bits vary with how work was split. Either compare with a tolerance, compute the sum sequentially where bit-exact output is required, or collect per-item values in order with `collect` and sum them with a sequential iterator.

  • par_iter().collect() returns items in completion order
  • for_each runs items in index order, just on more threads
  • reduce applies op strictly left to right like fold
  • A parallel f32 sum always equals the sequential sum
  • The identity closure in reduce is called exactly once