Sub topic 14
Choosing between messages and shared state
This chapter assumes you have read the earlier chapters on thread::spawn, move closures, Send and Sync, mpsc channels, and Arc<Mutex<T>>. You should be comfortable reading Result values from join, send, and lock. The goal is a set of criteria you can apply when a design could use either tool.
Two ways to coordinate threads
Rust gives you two main ways to let threads cooperate.
- Message passing moves values between threads through a channel. After
send, the sender no longer owns the value. At any moment one thread owns each piece of data. - Shared state keeps one value that several threads can reach, usually as
Arc<Mutex<T>>. Ownership of the value is shared, and the lock serializes access.
Both are safe, since the compiler rejects data races in either style. The choice affects other things: how easy the program is to reason about, how much waiting happens, how failures spread, and how memory use behaves.
Neither model is faster by default. A channel send costs an allocation or queue operation and a possible thread wake-up. A mutex lock costs an atomic operation when uncontended and a sleep and wake-up when contended. Measure before deciding on speed alone.
The same task both ways
Suppose four threads each add 1000 to a total. The shared-state version locks once per thread, after the work is done.
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let total = Arc::new(Mutex::new(0u64));
let mut handles = Vec::new();
for _ in 0..4 {
let total = Arc::clone(&total);
handles.push(thread::spawn(move || {
let partial: u64 = (1..=1000).map(|_| 1).sum();
*total.lock().unwrap() += partial;
}));
}
for h in handles {
h.join().unwrap();
}
println!("total = {}", *total.lock().unwrap());
}The message-passing version has each worker send its partial result, and the main thread does the adding.
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel::<u64>();
for _ in 0..4 {
let tx = tx.clone();
thread::spawn(move || {
let partial: u64 = (1..=1000).map(|_| 1).sum();
tx.send(partial).unwrap();
});
}
drop(tx);
let total: u64 = rx.iter().sum();
println!("total = {total}");
}Both print total = 4000. In the first, workers must know about the shared total, and the lock guards it. In the second, workers know nothing about each other. They only produce results, and one thread owns the accumulation. That difference grows as programs grow.
Decision criteria
| Question | Leans toward messages | Leans toward shared state |
|---|---|---|
| Does data flow in one direction, such as a pipeline or fan-in of results? | Yes | No |
| Do many threads read and write the same small piece of data in place? | No | Yes |
| Do you need work distributed among workers? | Yes, with a job channel | Only to protect the queue |
| Do you need backpressure? | Yes, `sync_channel` | No built-in mechanism |
| Does the value need to be read often by many threads? | Copying or cloning may be costly | `Arc<RwLock<T>>` or `Arc<Mutex<T>>` fits |
| Must a thread wait for something to happen? | `recv` blocks naturally | Needs a `Condvar` |
| How easy is it to see who changes the data? | One owner, easy to trace | Any lock holder, harder to trace |
A useful rule of thumb: if the thing you are moving is a unit of work or a result, use a channel. If the thing you are protecting is a long-lived piece of state that many threads touch, use a lock. Many programs need both.
Failure modes of each approach
Shared state: poisoning
If a thread panics while holding a MutexGuard, the mutex becomes poisoned. Later lock calls return Err(PoisonError). The data is still reachable through into_inner, but you must decide whether it is still consistent.
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let data = Arc::new(Mutex::new(vec![1, 2, 3]));
let d = Arc::clone(&data);
let result = thread::spawn(move || {
let mut guard = d.lock().unwrap();
guard.push(4);
panic!("failed while holding the lock");
})
.join();
println!("thread panicked: {}", result.is_err());
match data.lock() {
Ok(g) => println!("clean: {:?}", *g),
Err(poisoned) => {
let g = poisoned.into_inner();
println!("poisoned, data still readable: {:?}", *g);
}
}
}Calling unwrap on every lock, as the earlier examples do, turns one panic into a cascade of panics. That is often the right choice for small programs, because a half-updated invariant is a bug. For long-running services, decide deliberately.
Shared state: deadlock and lock scope
A mutex never causes a data race, but it can cause a deadlock. Two common causes:
- Two threads take two locks in opposite order. Fix this by always locking in the same order, or by restructuring so one lock covers both values.
- A thread locks the same non-reentrant
Mutextwice. The secondlockmay block forever or panic.
A quieter problem is holding a guard longer than you meant. A guard lives until the end of its scope, or until the end of the statement if it is a temporary. Compare the two lines below inside a worker that shares a receiver.
let job = job_rx.lock().unwrap().recv();The guard is a temporary, so it is dropped at the end of this statement. Other workers can then take the lock.while let Ok(job) = job_rx.lock().unwrap().recv() { ... }The temporary lives through the whole loop body. The lock stays held while the job runs, and your pool processes one job at a time.
This is why the worker pool in the previous chapter assigns the result to job first and matches on it afterward.
Message passing: hangs and unbounded growth
Channels have their own failure modes, and most come from closure rules.
- A forgotten sender hangs the receiver.
for msg in rxends only when everySenderis dropped. If the main thread keeps the originaltxalive, the loop never ends. Drop it before receiving, as the multiple-producer example did. - A dropped receiver turns
sendinto an error.sendreturnsErr(SendError)once theReceiveris gone. Decide whether that means "stop quietly" or "this is a bug". Anunwrapmakes it a panic. - An unbounded channel can fill memory.
mpsc::channelhas no limit. A fast producer and a slow consumer make the queue grow without bound. Usesync_channel(n)sosendblocks when the buffer is full. - Blocking
recvcan wait forever. If a thread must also do other work, usetry_recvorrecv_timeoutand treatDisconnectedseparately fromTimeout.
A bounded channel also has a deadlock: with sync_channel(0), send waits for a matching recv. If the same thread both sends and receives on it, it waits on itself.
Replacing a lock with an owner thread
When shared state is complex, you can often avoid the lock by giving the state to one thread and sending it commands. Other threads never touch the data. They ask the owner. This pattern is sometimes called an actor.
use std::collections::HashMap;
use std::sync::mpsc::{self, Sender};
use std::thread;
enum Command {
Add(String, u32),
Get(String, Sender<Option<u32>>),
}
fn main() {
let (tx, rx) = mpsc::channel::<Command>();
let owner = thread::spawn(move || {
let mut scores: HashMap<String, u32> = HashMap::new();
for cmd in rx {
match cmd {
Command::Add(name, n) => *scores.entry(name).or_insert(0) += n,
Command::Get(name, reply) => {
let _ = reply.send(scores.get(&name).copied());
}
}
}
});
let mut handles = Vec::new();
for _ in 0..4 {
let tx = tx.clone();
handles.push(thread::spawn(move || {
for _ in 0..250 {
tx.send(Command::Add("ana".to_string(), 1)).unwrap();
}
}));
}
for h in handles {
h.join().unwrap();
}
let (reply_tx, reply_rx) = mpsc::channel();
tx.send(Command::Get("ana".to_string(), reply_tx)).unwrap();
println!("ana = {:?}", reply_rx.recv().unwrap());
drop(tx);
owner.join().unwrap();
}The output is ana = Some(1000). Three details matter:
- The
HashMaplives inside one thread, so it needs noMutexand noArc. - A request that needs an answer carries its own reply
Sender. The caller then waits on a one-off channel. - Dropping the last
txends the owner'sforloop, so shutdown needs no extra signal.
The cost is that every access becomes a round trip. Reading one value takes two channel operations and two context switches. If many threads read tiny values at high frequency, a lock or RwLock is cheaper and simpler.
Mixing both: the worker pool
The worker pool from the last chapter used both models for different jobs.
- Job queue: a channel carries work in one direction. The
Receiveris notSync, so the workers share it throughArc<Mutex<Receiver<_>>>. The mutex protects the receiver handle, not your data. - Results: a second channel carries answers back to one collector.
- Shutdown: dropping
job_txcloses the queue and ends every worker loop.
This split is common. Use channels for the flow of work and results. Use a lock for a small, long-lived structure such as a cache, a configuration value, or a counter. If the channel carries large values, send ownership of the value (Vec<T>, Box<T>) rather than cloning it. A send of a Vec copies three words, not the elements.
Practical guidelines
- Start with the data's ownership. If one thread can own each value at any time, prefer channels.
- Keep critical sections short. Compute outside the lock and take it only to update.
- Never hold a guard across a blocking call such as
recv,join, or I/O. - Prefer bounded channels when the producer's speed is not under your control.
- Do not put a
Mutexaround a value just so a thread can read a constant. Share it withArc<T>, or borrow it withthread::scope. - Decide what a poisoned mutex or a failed
sendmeans for your program. Do not leave it to a reflexiveunwrap.
Exercises
Exercise
A worker loop is written as while let Ok(job) = rx.lock().unwrap().recv() { run(job); } where rx is an Arc<Mutex<Receiver<Job>>>. Four workers run this loop. Why do jobs run one at a time, and how do you fix it?
Show answer
In a while let the temporary MutexGuard from rx.lock().unwrap() lives for the whole loop body, so the lock stays held while run(job) executes. The other workers block on lock. Fix it by taking the job in a separate statement: let job = rx.lock().unwrap().recv(); and then matching on job. The guard is dropped at the end of the let statement, before the job runs.
Exercise
You are building a program where ten threads each parse a log file and the main thread must print one merged summary. Pick channels or Arc<Mutex<T>>, and give two reasons.
Show answer
Use channels. Data flows one way, from the parsers to one consumer, so each parser can send its partial summary and the main thread merges them, with no shared mutable value. Workers do not wait on each other for a lock, and ownership of each summary moves to the main thread. The main thread must drop its original Sender so that for summary in rx ends. A mutex version would also work, but then every worker has to know about the shared summary and take its lock.
Exercise
A producer reads records from disk much faster than a consumer can store them in a database. The program uses mpsc::channel. What happens, and what change addresses it?
Show answer
The unbounded queue grows without limit, because send never blocks. Memory use rises until the producer finishes or the process runs out of memory. Replace the channel with mpsc::sync_channel(n) for a suitable n. When the buffer is full, send blocks, so the producer slows to the consumer's speed.