skip to content

In Rust, why do Rayon's `for_each` and `map` demand `Fn + Sync + Send` closures, and why is locking a `Mutex` per item the wrong fix?

level: seniorimportance: should knowfreq 35%

answer

  1. called concurrently through a shared reference
  2. E0594 versus E0277
  3. compiles but serialises
  4. produce values, then combine

basics

~20 s

Rayon calls one closure concurrently from many workers, so it must be Fn (no mutating captures, else E0594) and Sync (shareable captures, else E0277). A per-item Mutex compiles but serialises the loop; fold plus reduce needs no lock.

solid answer

~40 s

Rayon's adapters are bounded `OP: Fn(Self::Item) + Sync + Send` because many workers call the same closure at once through `&`. Mutating a captured variable, `total += x`, fails with E0594 since the call expects `Fn` instead of `FnMut`; capturing a `RefCell` or an `Rc` fails with E0277, cannot be shared between threads safely. Wrapping the state in `Mutex` compiles and is correct, but every item contends for one lock, so the hot path runs serially and can be slower than the sequential loop. The idiomatic shape has each item produce a value that Rayon combines: `map` plus `collect` or `sum`, `fold` with a per-piece `HashMap` then `reduce` to merge, or `map_init` for per-job scratch state.

code

rust · 29 lines
rust
use rayon::prelude::*;
use std::collections::HashMap;
use std::sync::Mutex;

fn main() {
    let words: Vec<String> = (0..200_000).map(|i| format!("w{}", i % 1000)).collect();

    // Anti-pattern: compiles and is correct, but every item takes one lock.
    let shared = Mutex::new(HashMap::<&str, usize>::new());
    words.par_iter().for_each(|w| *shared.lock().unwrap().entry(w).or_default() += 1);
    let locked = shared.into_inner().unwrap();

    // Per-split maps with fold, merged pairwise with reduce: no lock at all.
    let folded = words
        .par_iter()
        .fold(HashMap::<&str, usize>::new, |mut m, w| {
            *m.entry(w).or_default() += 1;
            m
        })
        .reduce(HashMap::new, |mut a, b| {
            for (k, n) in b {
                *a.entry(k).or_default() += n;
            }
            a
        });

    assert_eq!(locked, folded);
    println!("{} distinct words, w7 seen {} times", folded.len(), folded["w7"]);
}

go deeper

for a junior

Recall that a Rayon closure cannot mutate a captured variable and that results should come back through map, collect or sum.

for a middle

Explain which bound each error comes from: E0594 from Fn, E0277 from Sync, and why a shared reference to a Sync type is fine to capture.

for a senior

Spot a per-item Mutex in review as serialised work, rewrite it with fold and reduce or map_init, and confirm the gain with a release-build measurement.

for a principal

Set the review rule that parallel loops return values instead of mutating shared state, and make an exception only where the shared write is rare and measured.

## Three ways a sequential loop body breaks under Rayon A sequential `for_each` happily mutates whatever it captures, because only one call runs at a time. Rayon's adapters declare stricter bounds. `ParallelIterator::for_each` is ```rust fn for_each<OP>(self, op: OP) where OP: Fn(Self::Item) + Sync + Send, ``` and `map`, `filter`, `fold` and `reduce` carry the same `Fn + Sync + Send` shape. Each part rules out one kind of race: - **`Fn`** (not `FnMut`): the closure is called through a shared reference, concurrently, so it may not mutate its captures. `total += x` inside it fails with **E0594**, "cannot assign to `total`, as it is a captured variable in a `Fn` closure", and rustc notes the call "expects `Fn` instead of `FnMut`". - **`Sync`**: several workers hold `&closure` at once, so everything it captures by reference must be shareable. A captured `RefCell<Vec<u64>>` fails with **E0277**, "`RefCell<Vec<u64>>` cannot be shared between threads safely", with a note pointing at the `Sync` bound on `for_each` in Rayon's source. A captured `Rc` fails the same way. Why those types are not thread-safe is covered with interior mutability and reference counting; the Rayon point is which bound caught them. - **`Send`**: the closure itself may move to another worker. These are compile errors, not runtime failures. Rayon's README states that its APIs guarantee **data-race freedom**, so in safe code these mistakes surface when you build, not in production. ## The fix that compiles but does not scale The first instinct is to wrap the shared state in a `std::sync::Mutex`: ```rust words.par_iter().for_each(|w| *shared.lock().unwrap().entry(w).or_default() += 1); ``` It compiles, because `&Mutex<HashMap<..>>` is `Sync`, and it is correct. But every item now takes the same lock, so the hot part of the loop runs one thread at a time, plus the cost of contention between threads. On a CPU-bound workload this can be **slower** than the sequential loop. A lock inside `par_iter` is a sign the chain is shaped like a sequential loop rather than a parallel computation. ## Idiomatic shapes: produce values, then combine Rayon's design is that each item **produces** a value and Rayon **combines** them: | Goal | Idiomatic Rayon shape | Shared state | |---|---|---| | one output per input | `par_iter().map(f).collect::<Vec<_>>()` | none | | a single total | `map(f).sum()` or `reduce(identity, op)` | none | | a map of counts or groups | `fold(HashMap::new, add_one).reduce(HashMap::new, merge)` | none | | per-job scratch buffers | `map_init(make_buffer, f)` or `for_each_init` | none | | one counter beside other work | `AtomicUsize::fetch_add` | one atomic | `fold` is the key tool for the counting case. It gives each piece of the split its **own accumulator**, created by the identity closure, and returns a parallel iterator of partial results; `reduce` then merges partials pairwise. No lock is taken, and the number of merges grows with the number of pieces, not with the number of words. The example builds the word counts both ways and asserts they are equal. When each item needs scratch state that is expensive to create, such as a reusable buffer or a hasher, `map_init(init, f)` calls `init` only as needed for each group of items in a Rayon job, not once per item, and passes `f` a `&mut` to it: mutation without sharing, because each job owns its own value. For a single scalar total, `sum()` or `reduce` is enough. An `AtomicUsize` is acceptable for one side counter, such as progress reporting, though its ordering choices belong to the material on atomics. A `Mutex` is still the right answer when the shared state is touched rarely compared with the per-item work. ## Diagnosing a parallel chain in review 1. **E0594 on a captured variable**: the body treats the closure as `FnMut`; turn the mutation into a returned value and a reduction. 2. **E0277 "cannot be shared between threads safely"**: a captured type is not `Sync`; borrow a `Sync` type instead (a plain `&Vec` or `&HashMap` works) or restructure. 3. **A `Mutex` or `RwLock` locked per item**: correct but serialised; replace with `map` + `collect`, `fold` + `reduce`, or `map_init` for per-job scratch state. 4. **Measure** the before and after in a release build; a parallel chain that is slower than the sequential one is common when the per-item work is small.

  • How does `fold` followed by `reduce` count words without any lock?
    `fold(HashMap::new, add)` gives each piece of Rayon's split its own map, created by the identity closure, and returns a parallel iterator of partial maps. `reduce(HashMap::new, merge)` then combines partials pairwise. Each map is owned by one worker while it is filled, so nothing is shared mutably, and the number of merges depends on how many pieces there are, not on how many words.
  • When is a `Mutex` inside a Rayon closure acceptable?
    When the lock is taken rarely relative to the per-item work: for example, each item does milliseconds of hashing and occasionally records an error in a shared `Vec`. Contention is then negligible. It is the wrong tool when every item locks it, because the hot path is serialised; there, return values and let `collect`, `fold` or `reduce` combine them.

  • Rayon closures can be FnMut as long as items are Send
  • A Mutex per item keeps the loop as fast as before
  • Rayon detects data races at run time and panics
  • RefCell is enough because each item is processed once
  • fold returns one final value like Iterator::fold