Sub topic 15
Shared state or message passing: choosing
This chapter assumes you know Arc<Mutex<T>>, lock guards, thread::spawn and move closures. It also assumes you have met RwLock, atomics and scoped threads from earlier chapters. Here you will choose between them and message passing.
Two models of coordination
Shared state means several threads touch the same value, and a lock decides who goes first. Arc<Mutex<T>> is the standard form.
Message passing means one thread owns a value at a time. Threads hand data to each other through a channel. The Rust standard library provides std::sync::mpsc, where "mpsc" means multiple producers, single consumer.
Both are safe in Rust. The difference is design. With shared state, every thread must agree on the lock and its ordering. With channels, the data flow is explicit, and sending a value moves ownership, so the sender can no longer touch it.
The same job with a channel
Four workers each compute a value. Instead of pushing into a locked Vec, they send results to the main thread.
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
for id in 0..4 {
let tx = tx.clone();
thread::spawn(move || {
let result = id * 10;
tx.send(result).unwrap();
});
}
drop(tx); // close the original sender so the receiver can finish
let mut values: Vec<i32> = rx.iter().collect();
values.sort();
println!("{:?}", values);
}This prints [0, 10, 20, 30]. The drop(tx) call matters. rx.iter() ends only when every sender is gone. If you keep the original tx alive, the loop waits forever.
There is no lock, no guard and no poisoning. Only the main thread ever holds the collected data.
Decision criteria
Ask what the threads are doing with the data.
| Situation | Good fit |
|---|---|
| Workers produce results for one collector | Channel |
| A pipeline of stages, each transforming data | Channels between stages |
| Many threads update one shared structure, such as a cache | `Arc<Mutex<T>>` |
| Mostly reads, rare writes | `Arc<RwLock<T>>` |
| A single counter or flag | Atomic type |
| Threads only need to borrow local data briefly | Scoped threads |
| A thread must sleep until a condition changes | `Condvar` or a channel |
Trade-offs to weigh
- Ownership clarity. Channels make ownership transfer visible. Locks hide who is using the data at any moment.
- Shared lookup. A channel is awkward when many threads must read and update the same map. A mutex fits better, because every thread sees the latest state.
- Backpressure.
mpsc::channelis unbounded, so a fast producer can grow memory without limit.mpsc::sync_channel(n)blocks senders whennmessages are waiting. - Failure handling. A mutex can be poisoned. A channel reports failure through
sendandrecverrors when the other side has been dropped. - Cost. Sending a large value moves it cheaply if it is heap-allocated, such as a
Vec. A short lock on a small value is often cheaper than a message.
Exercise
Exercise
Eight worker threads each compute a checksum of a file and you need all eight checksums in the main thread. Should you use Arc<Mutex<Vec<u64>>> or an mpsc channel? Name one thing you must do so that rx.iter() finishes.
Show answer
A channel is the better fit, because data flows one way from workers to one collector and no thread needs to read the shared collection while others write. To make rx.iter() finish, drop the original tx after cloning it for each worker, so that all senders are gone once the workers finish. A mutex-protected Vec also works, but it adds locking that the problem does not need.