Sub topic 15
Shared state or message passing: choosing
This chapter assumes you can already use Arc<Mutex<T>>, spawn threads with move closures, and read Result values. You have now seen shared state with Arc, Mutex, RwLock, atomics and Condvar. Rust's standard library also offers message passing through channels, and often it is the better fit. This chapter gives you a way to choose between the two.
Two models, one question
Both models answer the same question: how does data written by one thread reach another thread?
- Shared state: several threads hold a handle to one value. A lock or an atomic operation decides who touches it at a given moment.
- Message passing: each value has one owner at a time. To share information, a thread sends the value, or a description of the work, through a channel. Receiving a value means owning it.
The Rust documentation borrows a Go slogan for the second model: do not communicate by sharing memory, share memory by communicating. Rust does not force that choice. The compiler checks both models with the same ownership rules, so you choose on design grounds.
Message passing with mpsc
std::sync::mpsc provides a multiple-producer, single-consumer channel. mpsc::channel() returns a Sender<T> and a Receiver<T>. You can clone the sender for each producer thread. The receiver stays in one place.
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((id, result)).unwrap();
});
}
drop(tx);
let mut results: Vec<(i32, i32)> = rx.iter().collect();
results.sort();
println!("{:?}", results);
}This prints [(0, 0), (1, 10), (2, 20), (3, 30)]. Three details matter here:
sendmoves the value into the channel. The sender can no longer use it, so no two threads ever hold the same value.rx.iter()ends only when everySenderhas been dropped. The originaltxbelongs tomain, so the code drops it explicitly. If you forget, the loop waits forever.sendreturnsErrif the receiver has been dropped. Theunwraphere is acceptable in a demo. In real code you usually treat that error as a signal to stop the producer.
Notice what is missing: there is no Arc, no Mutex and no guard. Each worker computes its result privately and hands it over.
The owner-thread pattern
Channels also replace a mutex when many threads need to read or change one piece of state. Give the state to a single thread. Other threads send it commands, and the owner applies them one at a time. The queue inside the channel does the job the lock did before.
use std::sync::mpsc;
use std::thread;
enum Command {
Add(u64),
Get(mpsc::Sender<u64>),
}
fn main() {
let (tx, rx) = mpsc::channel();
let owner = thread::spawn(move || {
let mut total = 0;
for cmd in rx {
match cmd {
Command::Add(n) => total += n,
Command::Get(reply) => reply.send(total).unwrap(),
}
}
});
let mut handles = Vec::new();
for i in 1..=4 {
let tx = tx.clone();
handles.push(thread::spawn(move || tx.send(Command::Add(i)).unwrap()));
}
for handle in handles {
handle.join().unwrap();
}
let (reply_tx, reply_rx) = mpsc::channel();
tx.send(Command::Get(reply_tx)).unwrap();
println!("{}", reply_rx.recv().unwrap());
drop(tx);
owner.join().unwrap();
}The program prints 10. The total variable lives on one thread's stack and is never shared. A Get command carries a reply Sender, which is how a caller asks a question and receives an answer. The owner exits when all senders are gone and the for loop over rx ends.
This pattern cannot deadlock on a lock, because there is no lock. It can still stall if two threads wait for each other's replies, so the underlying risk is not gone. It has moved from "lock order" to "who waits for whom".
Comparing the two
| Concern | `Arc<Mutex<T>>` | Channels |
|---|---|---|
| Data location | One value, many handles | One owner at a time |
| Cost of an update | Lock, change, unlock | Allocate and send a message, then the owner applies it |
| Reading current state | Lock and read | Send a request and wait for a reply |
| Failure when a worker panics | Mutex is poisoned | Sender is dropped, and the receiver sees the channel close |
| Main hazards | Long critical sections, deadlock, poisoning | Unbounded queue growth, forgotten senders, reply cycles |
| Fits best | Small shared records, caches, counters | Pipelines, work queues, results flowing one way |
Two points in the table deserve a closer look.
First, the channel from mpsc::channel() is unbounded. A fast producer and a slow consumer make the queue grow until memory runs out. mpsc::sync_channel(n) creates a bounded channel. send blocks when n messages are waiting, which gives you backpressure for free.
Second, a lock makes reading cheap. A channel makes reading a round trip. If many threads need the current value of a setting hundreds of times per second, sending a Get command for each read is a poor design. RwLock or an atomic suits that case.
A decision guide
Work through these questions in order.
- Is the shared data a single number or flag? Use an atomic. It needs no lock and cannot be poisoned.
- Do threads only need to borrow data that outlives the work? Use scoped threads and plain references. Add a
Mutexonly if they also write. - Does data flow in one direction, such as tasks to workers or results to a collector? Use a channel. This is the pipeline shape, and it keeps ownership simple.
- Is it a small value that many threads read and update briefly? Use
Arc<Mutex<T>>, orArc<RwLock<T>>if reads dominate. - Must a thread sleep until some condition becomes true? Use
Condvarwith itsMutex, or a channel if the condition can be expressed as "a message arrived". - Does the state have complex invariants that several operations must keep consistent? Consider the owner-thread pattern. All logic lives in one place, so you reason about it sequentially.
The guide is a starting point. Some designs combine tools, such as workers that receive tasks over a channel and also update a shared cache behind an RwLock.
Mixing models without trouble
A few rules keep mixed designs manageable.
- Do not send an
Arc<Mutex<T>>through a channel just to share it. If you are passing a shared handle, the channel adds nothing. Pass the data itself, or rethink who owns it. - Do not hold a lock while calling
sendorrecv. A blocking channel call under a guard can stall every other thread that wants the lock, and it can deadlock if the other side needs the same lock. - Keep message types small and explicit. An
enumof commands, likeCommandabove, documents what the owner thread can do and letsmatchcheck that you handle every case. - Prefer moving data to cloning it. Large buffers should travel by value (a
Vec<u8>moves in constant time) rather than being copied into each message.
Where each choice goes wrong
Shared state fails quietly when critical sections grow. One slow operation under a lock turns a parallel program into a sequential one. Channels fail quietly when the queue grows. Neither failure produces a compile error or a crash, so measure when performance matters.
A related cost is design clarity. Shared state spreads the rules for a value across every place that locks it. Message passing puts the rules in the receiving loop. For a value with several invariants, the second layout is usually easier to review. For a plain counter it is more machinery than the problem needs, and an AtomicUsize is the better answer.
Exercises
Exercise
Four worker threads each compute a partial sum and the main thread needs the total. Would you use Arc<Mutex<u64>> or an mpsc channel, and why? What must you do with the original Sender so that the main thread's receive loop ends?
Show answer
Either works, but a channel fits better because data flows one way, from workers to main, and no worker needs to see another's result. Each worker sends its partial sum, and main adds them as they arrive. This avoids a lock entirely. The original Sender must be dropped (with drop(tx)) after cloning one for each worker. Otherwise rx.iter() never sees the channel close and the loop waits forever.
Exercise
A web server keeps a configuration map that is read on every request and replaced a few times per hour. Which tool from this chapter's decision guide fits, and why is the owner-thread pattern a poor fit here?
Show answer
Arc<RwLock<HashMap<..>>> fits, because reads dominate and many readers can hold the lock at once. The owner-thread pattern makes every read a round trip: send a Get command, wait for the reply. With a request on every read, the owner thread becomes a bottleneck, and the added latency buys nothing because the data has no complex invariants to protect.