Rust · Chapter 20 of 26

Threads

By the end of this chapter you can run code on several threads at once with std::thread::spawn, wait for them with join and collect what each returned, give a thread its own data with move (and read E0373 when you forget), borrow data in threads with thread::scope, handle a thread that panicked, and measure what running at once buys. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.

  • Part: Concurrency and services
  • 4 tasks
  • Rust
  • In the all labs plan

The first 2 chapters of Rust are free. This one comes with the all labs plan.

Why you need this

At 9 am every one of the 120 collection boxes sends its morning shift to the dairy plant, and the plant's service sends each society's pourings on in one upload. Each upload takes about 20 ms: most of that is the plant's answer travelling back over a village mobile network. Here are the 120 morning uploads made the way every program in this lab has run so far, one statement after another:

let plant = Plant::new();
let start = Instant::now();
for (id, cans) in &shifts {
    plant.upload(id, cans).unwrap();
}
one at a time: 120 uploads in 2.52s, at most 1 at once

Two and a half seconds, and the program's own work in them is almost nothing: it sends, then waits, 120 times in a row. The second upload cannot start until the first has come back, because a program you have written so far does exactly one thing at a time. When a line is down and each upload waits a second, the whole morning waits two minutes. Threads let the uploads wait side by side, so the morning costs about as long as the slowest one.

What you build: 4 tasks

Each task has tests. You write the code in the lab's editor and press Check.

  1. Task 1

    morning.rs: every society's morning, a thread each

    Write upload_morning(plant: &'static Plant, shifts: Vec<(String, Vec<Collection>)>) -> usize. For each (society, pourings) pair it calls plant.upload(&society, &pourings) on a thread of its own made with thread::spawn, all at the same time; it waits for every thread, and returns how many uploads succeeded (returned Ok).

    The Check gives it the morning of all 120 societies, with a plant that takes 20 ms an upload: it must return 120, the plant must have stored all 120 uploads the moment it returns (S001's 211 pourings, S014's 66, S120's 49), with exactly 120 uploads, at least 10 of them running at once (max_in_flight), in well under the 2.4 seconds one at a time takes (under 1.5 s). With S014's line down it returns 119, and with no societies, 0.

  2. Task 2

    totals.rs: the day's totals in four scoped threads

    Write day_totals(pourings: &[Collection]) -> (u64, u64): the sum of every pouring's ml, and the sum of every pouring's paise. Split the slice into four chunks of nearly the same size (the size is the length divided by 4, rounded up), add up each chunk on its own thread started inside thread::scope, and add the four results together.

    For Tuesday's 10,164 pourings it returns (82698770, 293257264). For no pourings it returns (0, 0), and for 1, 3, 5 and 10 pourings their own sums. The Check also looks for scope and spawn in totals.rs.

  3. Task 3

    receipts.rs: receipts in society order

    Write receipts(plant: &Plant, shifts: &[(String, Vec<Collection>)]) -> Vec<Result<Receipt, PlantError>>. It uploads each pair on a thread of its own, all at once, inside thread::scope (the threads borrow the plant and the pourings), and returns what each plant.upload returned, in the same order as shifts: element i is the result for shifts[i], an Err included.

    The Check gives it all 120 evenings in reverse (S120 first), then S999, with a plant that takes 20 ms and has S014's line down: it must return 121 results, each society's receipt in its own place, Err(PlantError::Down("S014")) in S014's place and Err(PlantError::UnknownSociety("S999")) last, with at least 10 uploads at once, in under 1.5 seconds.

  4. Task 4 · interview question

    Interview: report.rs, the report thread

    Write spawn_report(society: String, pourings: Vec<Collection>) -> JoinHandle<String>. It starts a thread (thread::spawn) that works out the shift report and returns the thread's handle at once. Joining the handle gives exactly "S014 morning: 66 pourings, 4 rejected, 655230 ml, 2165708 paise" for S014's morning: the society, the first pouring's shift, how many pourings, how many have Status::Rejected, and the sums of ml and paise. The Check also tries S120's evening. With no pourings, the thread panics with "no pourings for S061" (its society), so joining gives an Err.

    Farhan will ask: why does the compiler insist on move here, and what would go wrong if the thread borrowed society?

What you will learn

  • thread::spawn: start a closure running on a new thread.
  • join: wait for a thread, and get back what its closure returned.
  • move closures: give a thread its own data; E0373 when you forget.
  • thread::scope: threads that may borrow, because the scope waits for them.
  • A panic in a thread: it ends that thread, and join returns an Err.
  • What it buys: 120 uploads one at a time and at once, measured, and max_in_flight.

More in Concurrency and services

Build "Threads" yourself

DoodhSetu runs the milk collection boxes of 120 village societies around Anand. The old box program crashed on an empty line, and you rebuild it in Rust. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.

The first 2 chapters of Rust are free. This one comes with the all labs plan.