Threads

Threads in Rust: The dispatcher writes out four jobs and sends four vans. From the moment a van is through the gate it is on its own: it does not check back,…

The Analogy: Four Vans Sent Out At Nine

The dispatcher writes out four jobs and sends four vans. From the moment a van is through the gate it is on its own: it does not check back, the dispatcher has no idea where it is, and the only thing anybody can be sure of is that all four are moving at the same time. Whatever the depot was doing before nine, it is now doing five things at once.

Then there is the question of what each driver takes with them. A driver cannot be handed the noticeboard off the office wall -- they would carry it around all morning, and they might still have it when the office shuts. So a driver takes either a photocopy or the original of something the office has finished with. Anything that goes into a van has to be something the van can own outright for as long as it is out, because nobody at the depot can say in advance when that will be.

They come back in whatever order the traffic decided. Sometimes that is the order they left in; more often it is not, and nothing about the order is a fault. If the dispatcher writes the dockets down as they arrive, the sheet comes out differently every day. If he stands at the gate and asks for job one, then job two, then job three, the sheet comes out the same every day -- and the vans still ran at the same time. The order of the results is his decision. The order of the work never was.

Two things can go wrong. A van can come back with the job not done: that does not shut the depot, but the docket says so, and somebody has to actually read it. And if the dispatcher locks up without waiting at the gate, whatever the vans were in the middle of simply stops mattering to anyone. The work was only ever guaranteed to be started.


Syntax or Core Structure

thread::spawn starts a closure on a new operating-system thread and hands you a receipt for its result.

use std::thread;

fn main() {
    let mut handles = Vec::new();

    for bay in 1..=4 {
        let handle = thread::spawn(move || {
            let units = bay * 10;

            (bay, units)
        });

        handles.push(handle);
    }

    println!("spawned {}", handles.len());

    let mut total = 0;

    for handle in handles {
        let (bay, units) = handle.join().unwrap();

        println!("bay {bay}  units {units:3}");

        total += units;
    }

    println!("total {total}");
}

Output:

spawned 4
bay 1  units  10
bay 2  units  20
bay 3  units  30
bay 4  units  40
total 100

All four threads were running before the first join was called, and yet the four lines come out in bay order every single time. That is the dispatcher at the gate: join blocks until that thread finishes, so asking for the handles in order produces results in order without making the work sequential.

spawn returns a JoinHandle<T> where T is whatever the closure returned -- here a tuple. join() consumes the handle and gives back a Result, because the thread might have panicked instead of finishing. And the move is not optional: without it the closure would borrow bay from a loop that is about to end.

What it means
thread::spawn(f)Starts f on a new OS thread straight away and returns a JoinHandle<T>
handle.join()Blocks until that thread has finished, then yields its Result
move on the closureOwnership of everything captured is transferred into the thread
the 'static boundThe closure may outlive the frame that spawned it, so it may not borrow from it
the Send boundEverything moved in must be safe to hand to another thread
dropping a handleThe thread carries on, and its result can never be collected

Technical Depth: What Goes Into The Van

Why move, and what 'static is really refusing

use std::thread;

fn main() {
    let manifest = vec![String::from("a-01"), String::from("b-02")];

    let handle = thread::spawn(move || manifest.len());

    println!("rows {}", handle.join().unwrap());

    let label = String::from("depot");

    let named = thread::spawn(move || format!("{label}-ready"));

    println!("{}", named.join().unwrap());
}

Output:

rows 2
depot-ready

Drop the move from either closure and the compiler says the same thing both times:

error[E0373]: closure may outlive the current function, but it borrows `manifest`, which is owned by the current function
help: to force the closure to take ownership of `manifest` (and any other referenced variables), use the `move` keyword

The reason is in the signature:

pub fn spawn<F, T>(f: F) -> JoinHandle<T>
where
    F: FnOnce() -> T + Send + 'static,
    T: Send + 'static,

'static here does not mean "lives until the program ends". It means "contains no borrow that could expire", which for a spawned thread is the only honest requirement: the compiler cannot know when the thread stops, so it has to assume never. Send is the other half -- it is why an Rc cannot go into a spawn while an Arc can, and why that error usually names Send on some outer type rather than the Rc that caused it.

Note also what move costs on the caller's side: manifest is gone after the spawn, and using it again is E0382, use of moved value.

Borrowing anyway, with thread::scope

use std::thread;

fn main() {
    let bays = vec![118, 124, 7, 131];
    let mut totals = Vec::new();

    thread::scope(|s| {
        let mut workers = Vec::new();

        for chunk in bays.chunks(2) {
            workers.push(s.spawn(move || chunk.iter().sum::<i32>()));
        }

        for w in workers {
            totals.push(w.join().unwrap());
        }
    });

    println!("chunks {:?}", totals);
    println!("total  {}", totals.iter().sum::<i32>());
    println!("kept   {:?}", bays);
}

Output:

chunks [242, 138]
total  380
kept   [118, 124, 7, 131]

Each worker received a &[i32] pointing straight into bays. No Arc, no clone, no 'static, and the last line proves bays was never moved. thread::scope can allow this because it guarantees something spawn cannot: every thread started inside the scope has finished before scope returns, whether you joined it yourself or not. The borrow is therefore provably shorter than the data.

This is the right tool for "split this collection up, work on the pieces, put it back together", which is the majority of the threading most programs actually need.

The order that is yours and the order that is not

use std::thread;

fn main() {
    let mut handles = Vec::new();

    for bay in ["a", "b", "c"] {
        handles.push(thread::spawn(move || {
            println!("  inside {bay}");

            bay.to_uppercase()
        }));
    }

    let done: Vec<String> = handles.into_iter().map(|h| h.join().unwrap()).collect();

    println!("collected {done:?}");
}

Output, from one run of many. The three indented lines can appear in any order, and do:

  inside a
  inside c
  inside b
collected ["A", "B", "C"]

The last line is stable across every run; the three above it are not. Nothing coordinated them, so nothing decides their order except the scheduler. This is the single most useful habit in the lesson: threads should return their results, not print them. A report assembled after the joins is reproducible and testable, and one assembled by three threads shouting at the same file handle is neither.

ConstructOrder it gives you
spawn calls in a loopNone. Spawn order is not start order and start order is not finish order
printing inside a threadNone, and interleaving can split a single line on some platforms
joining handles in sequenceExactly the sequence you joined in, every run
sorting the collected resultsWhatever you sorted by, every run

A thread that panics

use std::thread;

fn main() {
    let good = thread::spawn(|| 42);
    let bad = thread::spawn(|| -> i32 { panic!("bay door jammed") });

    let good_result = good.join();
    let bad_result = bad.join();

    println!("good {}", good_result.is_ok());
    println!("bad  {}", bad_result.is_err());

    if let Err(payload) = bad_result {
        if let Some(text) = payload.downcast_ref::<&str>() {
            println!("why  {text}");
        }
    }

    println!("main still running");
}

Output. The failing thread also writes its own panic message to stderr; only the four stdout lines are shown:

good true
bad  true
why  bay door jammed
main still running

A panic in a spawned thread does not bring the process down. It unwinds that thread, and join reports it as Err carrying the panic payload -- Box<dyn Any + Send>, which is why getting the message back out requires a downcast_ref. Ignore that Err, or unwrap it, and a failure that the program could have described becomes a failure that the program merely has.

The asymmetry is worth remembering: a panic in main ends the process and every running thread with it, mid-instruction, with no unwinding and no destructors.


Real World Example: Four Workers On One Pasted Column

A batch of rows, split four ways, checked in parallel, merged into one report that reads the same on every run.

use std::thread;

struct Summary {
    worker: usize,
    rows: usize,
    good: usize,
    bad: usize,
    units: u32,
}

fn check(worker: usize, rows: &[&str]) -> Summary {
    let mut good = 0;
    let mut bad = 0;
    let mut units = 0;

    for row in rows {
        match row.split_once('=') {
            Some((bay, value)) if !bay.is_empty() => match value.parse::<u32>() {
                Ok(n) => {
                    good += 1;
                    units += n;
                }
                Err(_) => bad += 1,
            },
            _ => bad += 1,
        }
    }

    Summary { worker, rows: rows.len(), good, bad, units }
}

fn main() {
    let rows = vec![
        "a-01=118", "a-02=124", "a-03=x", "b-01=7",
        "b-02=131", "=5", "c-01=40", "c-02=",
    ];

    let workers = 4;
    let per = rows.len() / workers;

    let summaries: Vec<Summary> = thread::scope(|s| {
        let handles: Vec<_> = rows
            .chunks(per)
            .enumerate()
            .map(|(i, chunk)| s.spawn(move || check(i, chunk)))
            .collect();

        handles.into_iter().map(|h| h.join().unwrap()).collect()
    });

    let mut rows_seen = 0;
    let mut good = 0;
    let mut bad = 0;
    let mut units = 0;

    for s in &summaries {
        println!(
            "worker {}  rows {}  good {}  bad {}  units {:3}",
            s.worker, s.rows, s.good, s.bad, s.units
        );

        rows_seen += s.rows;
        good += s.good;
        bad += s.bad;
        units += s.units;
    }

    println!("merged rows {rows_seen}  good {good}  bad {bad}  units {units}");
    println!("workers {}  chunk size {per}", summaries.len());
}

Output:

worker 0  rows 2  good 2  bad 0  units 242
worker 1  rows 2  good 1  bad 1  units   7
worker 2  rows 2  good 1  bad 1  units 131
worker 3  rows 2  good 1  bad 1  units  40
merged rows 8  good 5  bad 3  units 420
workers 4  chunk size 2

thread::scope is carrying the design. Every worker holds a &[&str] that points directly into rows -- no Arc, no cloning, no 'static anywhere in the program -- and that is legal only because scope will not return until all four threads are done. Notice too that scope gives back whatever its closure evaluates to, so the whole parallel section is one expression producing a Vec<Summary>.

The report is byte-for-byte identical on every run, and that is a decision rather than good fortune. No thread prints anything. Each returns a Summary, the scope closes, and only then does main walk the vector in worker order. The version that printed from inside check would emit eight lines in scheduler order, which is untestable, and on some platforms would interleave halfway through a line.

The merge step is trivial because each Summary is nothing but counters that add up. That property is worth engineering towards rather than stumbling into: as long as the workers never need to see each other's partial results, spawn plus join is the entire coordination mechanism required. The moment they do -- a worker that must react to what another one found -- this shape stops being enough, and you need the channels of the next lesson or the shared lock of the one after it.

Now the limits, and the first one is uncomfortable. Four threads on eight rows is slower than one thread on eight rows: starting an OS thread costs orders of magnitude more than splitting two short strings, so this shape only earns anything when each chunk is genuine work. rows.len() / workers divides exactly here; hand it nine rows and chunks(2) yields five chunks and therefore five workers, quietly ignoring the workers variable that claims to control this. Nothing consults std::thread::available_parallelism, so 4 is a guess about a machine the program has never met. And check reports how many rows were bad but not which -- the per-row string it would need to build is exactly the kind of allocation that hands the parallel speedup straight back.


Common Mistakes

  1. Leaving out move and reading E0373 as a lifetime puzzle. It is not a puzzle. The closure borrows something the current frame owns, and the frame will very likely end first. Add move, or use thread::scope.
  1. Spawning and never joining. When main returns, the process exits and every running thread stops where it is. Output goes missing, files are left half-written, and the code looks correct.
  1. Assuming spawn order is run order. It is not. The second thread can finish before the first has started. Nothing in spawn promises anything about sequence.
  1. Printing from inside spawned threads. Interleaved and unreproducible, and on some platforms a single println! can be split by another thread's output. Return the text and print it after joining.
  1. .join().unwrap() as the permanent solution. It converts a described failure in a worker into an undescribed panic in main. Match on the Result and say what failed.
  1. Reaching for Arc reflexively. If every thread finishes inside the current function, thread::scope lets them borrow and costs nothing. Arc is for threads that genuinely outlive the frame.
  1. One thread per item. Ten thousand rows is not ten thousand threads; each one is a real OS thread with its own stack. Chunk the work to the number of cores, not the number of items.
  1. Expecting a thread panic to stop the program. It does not. Unless somebody reads the Err from join, a worker can fail completely and the run will report success.
  1. Trying to move an Rc into a thread. Rc is not Send, and the error frequently points at some struct several layers up that contains one. Arc is the replacement, and it is not a free swap -- its counters are atomic.

Best Practices

  • Try thread::scope first. Reach for spawn with move and Arc only when a thread must outlive the function that started it.
  • Have threads return data rather than print it. Assemble every report after the joins, in an order you chose.
  • Join in a deliberate sequence when you want a deliberate sequence. Parallel execution and ordered results are not in conflict.
  • Handle the Err from join. At minimum, name which worker failed; at best, downcast_ref the payload and log the message.
  • Size the pool from std::thread::available_parallelism rather than a literal, and remember it returns a Result.
  • Give each thread enough work to be worth its own creation. If a chunk takes less time than spawning a thread, do it on the caller.
  • Design each worker's result so that merging is addition or concatenation. Anything harder is a sign the work was not actually independent.
  • For real parallel workloads over collections, know what these primitives do and then consider a library built on them. Hand-rolled pools are easy to write and hard to get right.

Practice Exercises

  1. Take the first example, delete move, and read the error and its help line carefully. Put move back, then delete the join loop and replace it with println!("done"). Run it several times and describe what happens to the four bay lines.
  1. Make one worker in the four-worker example panic on a particular row. Confirm the process still finishes, then change the merge loop so the report names the worker that failed instead of unwrap-ing it away.
  1. Rewrite the four-worker example with Arc<Vec<String>> and plain spawn instead of thread::scope. List everything that got worse: the allocations, the 'static bound, and what now happens if you forget a join.
  1. Size the pool from std::thread::available_parallelism, falling back to 1 if it errors, and make the split produce exactly that many chunks even when the row count does not divide evenly. Verify the merged totals are unchanged.