Rust · Chapter 22 of 26
Shared state
By the end of this chapter you can share one value between many threads with Arc, change it safely with a Mutex or a RwLock, count with an atomic, say why Rc cannot cross into another thread (Send and Sync), spot a deadlock from two locks taken in different orders, and choose between a lock and a channel. 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 the plant's service has a thread for every collection box that is sending its morning: up to 120 at once. They all need the same few values. Ishita's screen shows one number, the cans accepted so far today, and every box thread adds its cans to it. Every thread prices cans from the same two rate charts, and at 11 am Neha changes the cow chart: from that moment every thread must use the new one, and no thread may ever price a can from half of the old chart and half of the new. Lakhan wants each society's paise for the day in one map that every thread adds to.
The Rust you know cannot do this yet. A thread from chapter 20 can borrow a value, but only to read it: the borrow rules allow many readers or one writer, so two threads that both add to the same counter do not compile. A channel from chapter 21 works when one thread owns the value and the others send it messages, but Ishita's number and the rate chart are read by everyone, all the time. Rc from chapter 19 shares a value between many owners, and the compiler refuses to send it to another thread at all. This chapter gives you the types that share a value between threads and let them change it, one at a time, safely.
What you build: 4 tasks
Each task has tests. You write the code in the lab's editor and press Check.
- Task 1
counter.rs: a can counter every thread can add to
Write two counters that many threads can share behind an Arc. MutexCounter keeps its count in a Mutex<u64>, and AtomicCounter keeps its count in an AtomicU64: give each struct that field. Both have the same three methods:
new() returns a counter that starts at 0.
add(&self, cans: u64) adds cans to the count.
get(&self) returns the count so far, a u64.
add takes &self, not &mut self, because many threads hold the counter at the same time, so the change must go through the Mutex or the atomic. The Check shares each counter with 8 threads that each add 1 ten thousand times, and get() must then return 80000. It gives 4 threads a quarter of Tuesday's pourings each, and they add 1 for every accepted pouring: 9864. A new AtomicCounter given add(5) then add(7) returns 12. The file must use both Mutex and AtomicU64.
- Task 2
rates.rs: one rate chart, read by many threads
Write RateBoard, which keeps the rate charts (a Vec<Rate>, one for each kind of milk) in a RwLock, with three methods:
RateBoard::new(rates: Vec<Rate>) -> RateBoard keeps the charts it is given (the Check passes doodh::rates()).
price(&self, c: &Collection) -> u64 works out what the can earns with the chart for c.kind as it is now: 0 when c.fat is below the chart's min_fat or c.snf is below its min_snf; otherwise a litre is worth fat * fat_paise + snf * snf_paise paise, and the can earns (ml * that + 500) / 1000 paise. With doodh::rates(), price gives every one of Tuesday's pourings its own paise.
set(&self, rate: Rate) replaces the chart of rate.kind with rate and leaves the other kind's chart as it was.
With the cow chart (32 and 20), a cow can of 6000 ml at fat 41 and snf 86 earns 18192 paise. After set gives cow milk 34 paise for each tenth of fat (snf_paise 20, min_fat 30, min_snf 80), the same can earns 18684, and a buffalo can of 5000 ml at fat 62 and snf 90 still earns 19600. The Check prices from 4 threads at once, also while another thread calls set 200 times: every price must come from one whole chart (18192 or 18684, nothing else). The file must use a RwLock.
- Task 3
totals.rs: every society's paise, added up by many threads
Write society_totals(pourings: Vec<Collection>, threads: usize) -> HashMap<String, u64>. It splits pourings into threads parts as even as they can be, starts one thread for each part with thread::spawn, and every thread adds its pourings' paise into one HashMap behind an Arc<Mutex<..>>, keyed by society id. When every thread has finished, it returns the map.
Every society with a pouring has an entry (rejected cans add 0 paise); on Tuesday S001 earned 12415897 paise, and all 120 societies have an entry. The Check tries all of Tuesday's pourings with 4, 1 and 7 threads, 3 of S014's pourings with 8 threads, and no pourings at all with 4 threads, which must return an empty map. threads is always at least 1. The file must use Arc and Mutex.
- Task 4 · interview question
Interview: upload.rs, the Rc that would not cross
Lakhan's upload_all(plant: Arc<Plant>, shifts: Vec<(String, Vec<Collection>)>) -> Tally sends each society's pourings to the plant with plant.upload and keeps a Tally of what the plant stored. He wanted a thread for each society, but his tally is an Rc<RefCell<Tally>>, the compiler refused (error E0277, an Rc cannot be sent between threads safely), and so it uploads one society at a time.
Make it upload every society on its own thread, all at the same time, and join them all before returning. Keep the tally right: uploads counts the uploads the plant stored, and pourings and paise add up the pourings and paise of their receipts. A failed upload is not counted.
The Check uploads the morning of S001 to S040 with S014's line down: 40 uploads of 20 ms must run at the same time (more than one in flight) and take well under 500 ms (one at a time takes 800 ms), and the tally must count 39 uploads with those 39 societies' pourings and paise. No Rc or RefCell may be left in upload.rs.
Farhan will ask: why can an Rc not be sent to another thread, when an Arc can?
What you will learn
- Arc: shared ownership across threads, like Rc but safe to send.
- Mutex and its guard: one thread at a time may change the value, and the lock opens when the guard is dropped.
- RwLock: many readers at once, or one writer.
- AtomicU64: a number that threads can add to without a lock.
- Send and Sync: the two traits that say what may cross between threads, and why Rc is neither.
- Deadlock and poisoning: what goes wrong with locks, and how to avoid it.
More in Concurrency and services
Build "Shared state" 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.