Rust Playbook

Course › Week 3 · Iterators, real data, speed › Day 5 · lesson 19 of 42 · 15 min reading + 45–60 min practice

Parallelism with rayon

Use every core by changing iter() to par_iter(), and what Send and Sync mean.

rayonpar_iterthreadsSendSync

On this page
  1. 1. A thread
  2. 2. Send and Sync: what may cross a thread
  3. 3. rayon: change iter() to par_iter()
  4. 4. No shared counters
  5. 5. collect keeps the order
  6. 6. When parallel helps
  7. 7. A stream, in parallel batches
  8. Coming from PHP
  9. Practice
  10. Remember

A PHP request runs on one core. When Laravel needs more, it starts more processes: more queue workers, more PHP-FPM children. Rust can use every core inside one program, with threads, and the compiler checks that the threads cannot corrupt each other’s data. That check is why Rust people talk about “fearless concurrency”.

Today: one look at raw threads, the two traits that make them safe, and then rayon, the crate that turns iter() into par_iter() and does the thread work for you. You will rarely write a thread by hand.

1. A thread

thread::spawn runs a closure on a new thread and returns a handle. join() waits for it and gives back the closure’s result. The closure is move (as in the closures lesson) because it must own what it uses: the thread may outlive the code that started it.

src/main.rs
use std::thread;

fn main() {
    let scores: Vec<u64> = (1..=1_000_000).map(|n| n % 5 + 1).collect();
    let (first_half, second_half) = scores.split_at(scores.len() / 2);
    let first_half = first_half.to_vec();

    let handle = thread::spawn(move || first_half.iter().sum::<u64>());
    let second: u64 = second_half.iter().sum();

    match handle.join() {
        Ok(first) => println!("total {}", first + second),
        Err(_) => eprintln!("the worker thread panicked"),
    }
}
$ cargo run
total 3000000

The new thread sums one half while the main thread sums the other. join() returns a Result because the thread might have panicked; a panic in one thread does not crash the others.

to_vec() makes an owned copy of the first half to move into the thread. Splitting work, copying it across, and joining by hand is exactly the bookkeeping rayon removes in section 3.

2. Send and Sync: what may cross a thread

Two traits, implemented automatically by the compiler, decide what threads may touch. Send: a value can be moved to another thread. Sync: a value can be shared by reference between threads. Almost everything is both. One exception is Rc, a reference-counted pointer whose counter is not safe to change from two threads at once:

src/main.rsdoes not compile
use std::rc::Rc;
use std::thread;

fn main() {
    let settings = Rc::new(String::from("score scale: 1 to 5"));
    let shared = Rc::clone(&settings);

    let handle = thread::spawn(move || println!("{shared}"));
    let _ = handle.join();
}
cargo build
error[E0277]: `Rc<String>` cannot be sent between threads safely
 --> src/main.rs:8:32
  |
8 |     let handle = thread::spawn(move || println!("{shared}"));
  |                  ------------- -------^^^^^^^^^^^^^^^^^^^^^
  |                  |             |
  |                  |             `Rc<String>` cannot be sent between threads safely
  |                  |             within this `{closure@src/main.rs:8:32: 8:39}`
  |                  required by a bound introduced by this call
  |
  = help: within `{closure@src/main.rs:8:32: 8:39}`, the trait `Send` is not implemented for `Rc<String>`
note: required because `shared` is used within this closure
 --> src/main.rs:8:51
  |
8 |     let handle = thread::spawn(move || println!("{shared}"));
  |                                                   ^^^^^^
note: required by a bound in `spawn`
 --> /rustc/20ddd01716a87c0fcf06ae4752d85a4abc15bcdf/library/std/src/thread/functions.rs:125:0

For more information about this error, try `rustc --explain E0277`.
error: could not compile `hello` (bin "hello") due to 1 previous error

In another language this compiles and corrupts the counter once in a million runs. Here the thread-safe version is one word away: Arc (“atomic reference count”), which Rc is the cheaper single-thread form of. You will use Arc in Week 4 to share a database pool between tasks.

3. rayon: change iter() to par_iter()

cargo add rayon, import its prelude, and an iterator chain runs on every core: rayon splits the items into pieces, hands them to a pool of threads, one per core, and combines the results. The rest of the chain is unchanged.

src/main.rs
use rayon::prelude::*;

/// Lower-case letters and digits; anything else becomes one space: "Too  FAST!!" → "too fast".
fn normalise(comment: &str) -> String {
    let mut out = String::with_capacity(comment.len());
    for c in comment.chars() {
        if c.is_alphanumeric() {
            out.extend(c.to_lowercase());
        } else if !out.is_empty() && !out.ends_with(' ') {
            out.push(' ');
        }
    }
    out.trim_end().to_string()
}

fn main() {
    let comments: Vec<String> = (0..200_000)
        .map(|n| format!("Answer {n}:  The teacher was TOO fast, but clear!!"))
        .collect();

    let words: usize = comments
        .iter()
        .map(|c| normalise(c).split(' ').count())
        .sum();
    let words_parallel: usize = comments
        .par_iter()
        .map(|c| normalise(c).split(' ').count())
        .sum();

    println!("{words} words, in parallel {words_parallel}");
}
$ cargo run
1800000 words, in parallel 1800000

Same result, from the same chain, with par_ in front. Timed with --release on the 2-core machine this site is built on, the sequential sum took about 155 ms and the parallel one 86 ms (Rust 1.100.1): 1.8 times faster, not 2, because splitting and combining cost something. With more cores the gap grows; the exercise below measures it on yours.

normalise checks is_alphanumeric(), which is true for Arabic and other letters too, and turns any other character into a space, including non-ASCII punctuation like the Arabic comma ،. A rule that only knew ASCII punctuation would silently glue two Arabic words together. Free text from real surveys is not ASCII.

4. No shared counters

The loop habit, counting into a variable from inside the closure, does not compile with rayon: many threads would write to total at once.

src/main.rsdoes not compile
use rayon::prelude::*;

fn main() {
    let scores: Vec<u64> = vec![5, 4, 3, 2, 5];
    let mut total: u64 = 0;

    scores.par_iter().for_each(|score| total += score);

    println!("{total}");
}
cargo build
error[E0596]: cannot borrow `total` as mutable, as it is a captured variable in a `Fn` closure
 --> src/main.rs:7:40
  |
5 |     let mut total: u64 = 0;
  |         --------- `total` declared here, outside the closure
6 |
7 |     scores.par_iter().for_each(|score| total += score);
  |                       -----------------^^^^^----------
  |                       |        |       |
  |                       |        |       cannot borrow as mutable
  |                       |        in this closure
  |                       expects `Fn` instead of `FnMut`

For more information about this error, try `rustc --explain E0596`.
error: could not compile `hello` (bin "hello") due to 1 previous error

This is a data race, caught at compile time: rayon’s closures must be Fn, so they can only read what they capture. The fix is not a lock; it is to let rayon combine: scores.par_iter().sum(), or map each item to a value and sum, count or reduce them. Each thread totals its own piece, and rayon adds the pieces up.

5. collect keeps the order

Threads finish in any order, but a parallel map followed by collect into a Vec gives the results in the input order. So writing results in the same order as the rows you read is free:

src/main.rs
use rayon::prelude::*;

/// Lower-case letters and digits; anything else becomes one space: "Too  FAST!!" → "too fast".
fn normalise(comment: &str) -> String {
    let mut out = String::with_capacity(comment.len());
    for c in comment.chars() {
        if c.is_alphanumeric() {
            out.extend(c.to_lowercase());
        } else if !out.is_empty() && !out.ends_with(' ') {
            out.push(' ');
        }
    }
    out.trim_end().to_string()
}

fn main() {
    let comments = vec![
        "Too  FAST!!",
        "Clear explanations, thank you.",
        "شرح واضح جدا",
        "",
    ];

    let cleaned: Vec<String> = comments.par_iter().map(|c| normalise(c)).collect();
    for (before, after) in comments.iter().zip(&cleaned) {
        println!("{before:?} → {after:?}");
    }
}
$ cargo run
"Too  FAST!!" → "too fast"
"Clear explanations, thank you." → "clear explanations thank you"
"شرح واضح جدا" → "شرح واضح جدا"
"" → ""

zip walks two iterators side by side, here the comments and their cleaned versions. The Arabic comment kept its words, and the empty comment stayed empty instead of becoming a space.

6. When parallel helps

Workpar_iter?Why
Parsing, validating, normalising, hashing many itemsYesCPU-bound: each core takes a share
Adding up 10 numbersNoSplitting costs more than the work
Waiting on HTTP calls or a databaseNoThe cores are idle anyway; that is async, in Week 4
Writing results to one fileNoOne file is written in order: compute in parallel, write sequentially
Reading one fileNoThe disk reads in order; parallelise what happens to the lines

Measure before and after with --release. If the parallel version is not clearly faster, remove it: it adds threads for nothing.

7. A stream, in parallel batches

par_iter needs the items in memory, but a 1-million-row CSV should be streamed. The answer is batches: read a few thousand rows into a Vec, process the batch in parallel, write the results in order, clear the Vec, repeat. Memory holds one batch at a time. Here with a batch of 3, so you can see it:

src/main.rs
use rayon::prelude::*;

/// Lower-case letters and digits; anything else becomes one space: "Too  FAST!!" → "too fast".
fn normalise(comment: &str) -> String {
    let mut out = String::with_capacity(comment.len());
    for c in comment.chars() {
        if c.is_alphanumeric() {
            out.extend(c.to_lowercase());
        } else if !out.is_empty() && !out.ends_with(' ') {
            out.push(' ');
        }
    }
    out.trim_end().to_string()
}

const BATCH: usize = 3;

fn main() {
    let incoming = [
        "Too  FAST!!",
        "Clear, thank you.",
        "Needs more EXAMPLES",
        "ok",
        "Great teacher!",
    ];

    let mut batch: Vec<&str> = Vec::with_capacity(BATCH);
    for comment in incoming {
        batch.push(comment);
        if batch.len() == BATCH {
            process(&batch);
            batch.clear();
        }
    }
    if !batch.is_empty() {
        process(&batch); // the last, smaller batch
    }
}

fn process(batch: &[&str]) {
    let cleaned: Vec<String> = batch.par_iter().map(|c| normalise(c)).collect();
    println!("batch of {}: {cleaned:?}", cleaned.len());
}
$ cargo run
batch of 3: ["too fast", "clear thank you", "needs more examples"]
batch of 2: ["ok", "great teacher"]

Vec::with_capacity(BATCH) reserves room for a full batch once, and clear() empties the Vec but keeps that room, so the loop never reallocates. Forgetting the last partial batch is the classic bug of this pattern; the if after the loop is not optional.

This is the exact shape of the csv2json build, with a batch of 10,000 rows.

Coming from PHP

PHP’s answer to “use more cores” is more processes, coordinated through something outside them:

app/Jobs/NormaliseComments.php (part)
<?php

// Split the export into chunks and let Horizon's workers take them, one process per worker.
foreach (array_chunk($commentIds, 10_000) as $chunk) {
    NormaliseComments::dispatch($chunk);
}

That works, and it scales across machines, which threads do not. But each chunk pays for serialising the job, Redis, a separate process and its own memory, and nothing checks that two workers do not write to the same row. Inside one Rust program, the threads share memory directly, and the compiler rejects the version where they would overwrite each other.

PracticeThe Book ch. 16.1, Rustlings threads, and a measurement

Read chapter 16.1 of the Book, and the rayon README.

In Rustlings: 20_threads 1 and 2.

Exercise: measure it

Take section 3’s program and time each line with std::time::Instant::now() and .elapsed(). Run it with cargo run and with cargo run --release. Then make normalise trivial (return comment.len() only) and measure again. Write the four numbers down: they are the whole of section 6 in one experiment.

Show the timing code
src/main.rs (part of main)
    let start = std::time::Instant::now();
    let words: usize = comments.iter().map(|c| normalise(c).split(' ').count()).sum();
    println!("sequential: {words} words in {:?}", start.elapsed());

    let start = std::time::Instant::now();
    let words_parallel: usize = comments.par_iter().map(|c| normalise(c).split(' ').count()).sum();
    println!("parallel:   {words_parallel} words in {:?}", start.elapsed());

A debug build can be 10 to 50 times slower than --release, and it changes which version wins. Never measure speed without --release.

Remember

  • Change iter() to par_iter() for CPU-bound work on many items; measure with --release before keeping it.
  • Never share mutable state across threads: map and let rayon collect, sum or reduce.

Tomorrow is a build day: csv2json, 100K survey rows to JSON Lines with validation, in parallel batches, benchmarked against the same tool in PHP.