Sub topic 14
Choosing between messages and shared state
This chapter assumes you know how to spawn and join threads, use move closures, send values through mpsc channels, and share data with Arc<Mutex<T>>. It helps you pick one approach for a given problem.
Two models, one goal
Both tools let threads cooperate without data races. They differ in who owns the data.
- Message passing moves ownership of a value from one thread to another. After
send, the sender no longer has the value, so only one thread touches it at a time. - Shared state keeps one value alive in several threads. A
Mutexmakes them take turns.
When messages fit
Choose a channel when data moves through stages, such as a producer that reads input and a consumer that processes it.
- Each value has one owner at a time, so there is no lock to forget.
- Closing the channel is a built-in "no more work" signal. Dropping the last
Senderends the receiver's loop. sync_channeladds backpressure when the producer can outrun the consumer.- Threads stay loosely coupled. A consumer does not need to know how many producers exist.
The cost is that values move between threads. Large values are cheap to send if they are heap types like Vec or String, because only the pointer moves. A value that many threads need to read at once is awkward to send.
When shared state fits
Choose Arc<Mutex<T>> when several threads must read or update the same value, and no natural direction of flow exists. Common cases are counters, caches, and configuration that changes at runtime.
- Updates are direct. You lock, change, and unlock.
- Every thread sees the latest value.
The costs are real:
- Threads that wait for the lock do nothing. Heavy contention can make a program no faster than a single thread.
- Holding a guard across slow work, such as I/O, blocks everyone else.
- A thread that panics while holding the lock poisons the mutex. Later
lock()calls returnErr. - Locking two mutexes in different orders in different threads can deadlock.
A side-by-side example
Both programs count to 4000 using four threads. The first shares one counter. The second sends partial counts to one thread that adds them.
use std::sync::mpsc;
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
// Shared state: every thread updates one counter.
let counter = Arc::new(Mutex::new(0u32));
let mut handles = Vec::new();
for _ in 0..4 {
let counter = Arc::clone(&counter);
handles.push(thread::spawn(move || {
for _ in 0..1000 {
*counter.lock().unwrap() += 1;
}
}));
}
for h in handles {
h.join().unwrap();
}
println!("shared: {}", *counter.lock().unwrap());
// Message passing: each thread counts locally and sends one result.
let (tx, rx) = mpsc::channel::<u32>();
for _ in 0..4 {
let tx = tx.clone();
thread::spawn(move || {
let mut local = 0;
for _ in 0..1000 {
local += 1;
}
tx.send(local).unwrap();
});
}
drop(tx);
let total: u32 = rx.iter().sum();
println!("messages: {total}");
}The message version locks nothing and touches shared memory only at the end. The shared version locks 4000 times. For a plain counter, an atomic type would be lighter still, but that is outside this chapter.
Rules of thumb
| Situation | Prefer |
|---|---|
| Pipeline of stages | Channel |
| Work queue with many workers | Channel for jobs, plus workers |
| Shared cache or counter | `Arc<Mutex<T>>` |
| Threads only borrow local data and finish together | Scoped threads |
| Producer faster than consumer | `sync_channel` |
Many programs use both. The worker pool from the previous chapter sends jobs through a channel and shares the receiver behind Arc<Mutex<_>>.
Common mistakes
- Using a mutex where each thread could compute a partial result and return it from
join. - Holding a lock guard while calling
recvor doing slow work. - Forgetting to drop the original
Sender, so the receiving loop never ends. - Sending a handle to shared state through a channel when a plain value would do.
Exercise
A program has three threads that each parse a file and need to produce one combined word count at the end. Would you use a channel or an Arc<Mutex<HashMap>>, and why?
Show answer
A channel is usually better. Each thread builds its own local HashMap with no locking, then sends it to the main thread, which merges the three maps. This avoids lock contention during parsing. Alternatively, each thread can return its map through join. An Arc<Mutex<HashMap>> works, but every word insert would take the lock.
Exercise
Name two risks that apply to Arc<Mutex<T>> but not to a channel that moves values between threads.
Show answer
Any two of these: deadlock from locking mutexes in inconsistent order, a poisoned mutex after a panic while the lock is held, and slowdown from threads waiting on a contended lock.