Message Passing
local graph
Chapter 18 — Message Passing
Section titled “Chapter 18 — Message Passing”Verba volant, scripta manent. (Spoken words fly away, written words remain.)
Shared mutable state, despite Rust’s compile-time guarantees against data races, remains conceptually difficult. Developers must reason about which threads hold which locks, when locks should be acquired, and in what order to prevent deadlocks. The cognitive load increases with system complexity. Every new mutex introduces potential interactions with existing ones. Every new thread multiplies the possible interleavings to consider.
Message passing offers an alternative. Instead of multiple threads sharing access to the same data, each piece of data has a single owner at any moment. Threads communicate by sending messages through channels. When one thread sends data, it relinquishes ownership. When another receives, it gains exclusive access. No locks required. No shared state to synchronize. The ownership model that makes Rust’s single-threaded code safe extends naturally to concurrent communication.
This approach has deep roots. The actor model, formalized in the 1970s, builds entire systems from independent actors that communicate exclusively through messages. Erlang built a telecommunications empire on this foundation. Go popularized channels as first-class concurrency primitives. Rust’s ownership system makes message passing particularly natural: sending a value through a channel is the transfer of ownership, and the type system ensures you cannot access what you no longer own.
Channels: mpsc and beyond
Rust’s standard library provides channels through std::sync::mpsc, which stands for “multiple producer, single consumer.” The name describes the channel’s topology: many threads can send messages, but only one thread can receive them.
Creating a channel returns two halves: a Sender and a Receiver. The sender can be cloned to give multiple threads the ability to send. The receiver cannot be cloned; only one thread can own it.
use std::sync::mpsc;use std::thread;
fn main() { let (sender, receiver) = mpsc::channel();
thread::spawn(move || { sender.send("hello from thread").unwrap(); });
let message = receiver.recv().unwrap(); println!("Received: {}", message);}The send method takes ownership of the value being sent. After calling send, the spawned thread can no longer access the message. The recv method blocks until a message arrives, then returns ownership to the receiving thread. This transfer is not copying; the data moves from sender to receiver, with the channel serving as the conduit.
The send method returns a Result because sending can fail if the receiver has been dropped. When no receiver exists to accept messages, continuing to send would lose data. The Result lets the sender detect this condition and respond appropriately. Similarly, recv returns a Result that signals when all senders have been dropped and no more messages will arrive.
For scenarios where blocking is undesirable, try_recv checks for messages without waiting:
loop { match receiver.try_recv() { Ok(message) => println!("Got: {}", message), Err(mpsc::TryRecvError::Empty) => { // No message available, do other work do_other_work(); } Err(mpsc::TryRecvError::Disconnected) => { // All senders dropped, exit loop break; } }}Multiple producers arise naturally when several threads need to report results to a coordinator. Cloning the sender creates independent handles that all feed into the same channel:
use std::sync::mpsc;use std::thread;use std::time::Duration;
fn main() { let (sender, receiver) = mpsc::channel();
for id in 0..4 { let sender = sender.clone(); thread::spawn(move || { for i in 0..5 { thread::sleep(Duration::from_millis(100 * id as u64)); sender.send(format!("Worker {} message {}", id, i)).unwrap(); } }); }
drop(sender); // Drop the original sender
for message in receiver { println!("{}", message); }}The original sender must be dropped explicitly (or moved into a thread that finishes) because the receiver iterator continues until all senders are gone. With four clones in spawned threads plus the original, five senders exist. The spawned threads move their clones, which drop when the threads complete. The original must be dropped manually for the receiver’s iteration to terminate.
The receiver implements Iterator, allowing the idiomatic for message in receiver pattern. This loop receives messages until the channel closes, providing a clean way to process all incoming data.
Synchronous channels and backpressure
The standard channel() function creates an unbounded channel. Senders never block; messages accumulate in an internal queue. This can become problematic when producers generate data faster than consumers process it. Memory usage grows without limit. The system eventually exhausts resources.
Synchronous channels, created with sync_channel, address this through bounded capacity:
use std::sync::mpsc;use std::thread;
fn main() { let (sender, receiver) = mpsc::sync_channel(2); // Capacity of 2
thread::spawn(move || { for i in 0..10 { println!("Sending {}", i); sender.send(i).unwrap(); // Blocks when buffer is full println!("Sent {}", i); } });
thread::sleep(Duration::from_millis(500));
for value in receiver { println!("Received {}", value); thread::sleep(Duration::from_millis(100)); }}Running this code reveals the backpressure in action. The sender quickly fills the buffer with two messages, then blocks on the third send. Only when the receiver consumes a message does the sender proceed. This flow control prevents runaway memory growth and provides natural throttling when producers outpace consumers.
A capacity of zero creates a rendezvous channel. The sender blocks until the receiver is actively waiting. This provides tight synchronization: the sender knows the receiver has accepted the message, not that it waits in a buffer.
Beyond standard channels
The standard library’s mpsc channels serve many needs, but their single-consumer limitation constrains some designs. The broader ecosystem provides alternatives.
The crossbeam-channel crate offers multi-producer, multi-consumer channels with several additional features. Multiple threads can receive from the same channel, with each message going to exactly one receiver. This enables work-stealing patterns where a pool of workers draws from a shared task queue:
use crossbeam_channel::unbounded;use std::thread;
fn main() { let (sender, receiver) = unbounded();
// Spawn worker pool let mut handles = vec![]; for id in 0..4 { let receiver = receiver.clone(); // Receivers can be cloned handles.push(thread::spawn(move || { for task in receiver { println!("Worker {} processing: {}", id, task); } })); }
// Send tasks for i in 0..20 { sender.send(format!("Task {}", i)).unwrap(); }
drop(sender);
for handle in handles { handle.join().unwrap(); }}The crossbeam-channel crate also provides select!, enabling a thread to wait on multiple channels simultaneously and react to whichever receives first. This pattern proves essential for complex coordination:
use crossbeam_channel::{select, unbounded, Receiver};use std::time::Duration;
fn process_events( commands: Receiver<Command>, data: Receiver<Data>, shutdown: Receiver<()>,) { loop { select! { recv(commands) -> cmd => { match cmd { Ok(command) => handle_command(command), Err(_) => println!("Command channel closed"), } } recv(data) -> item => { match item { Ok(data) => process_data(data), Err(_) => println!("Data channel closed"), } } recv(shutdown) -> _ => { println!("Shutdown requested"); break; } default(Duration::from_secs(1)) => { println!("No activity for 1 second"); } } }}The select! macro blocks until one of the channels has data, then executes the corresponding branch. The default clause with a duration provides timeout functionality. This construct enables building responsive systems that handle multiple event sources without dedicated threads for each.
Designing systems with channels
Channels excel at structuring concurrent systems as pipelines, where data flows through stages of processing. Each stage runs in its own thread, receiving work from upstream and sending results downstream. The following diagram illustrates a typical data processing pipeline:
graph TD
subgraph DS["Data Sources"]
S1["Source 1"]
S2["Source 2"]
end
subgraph PR["Processing"]
P["Parser Thread"] -- channel --> V["Validator Thread"] -- channel --> T["Transformer Thread"]
end
subgraph OUT["Output"]
ST["Storage Thread"]
end
S1 -- channel --> P
S2 -- channel --> P
T -- channel --> ST
[!visual-conversion] Pipeline architecture with channels connecting stages. Print diagram (PDF 485, printed p. 477) recreated in Mermaid; frames and labels verbatim.
Each stage operates independently, processing items as they arrive. Backpressure propagates naturally: if storage slows down, the transformer’s output channel fills, causing it to slow, which backs up the validator, and so on. The system self-regulates without explicit coordination code.
Implementing a pipeline involves connecting channels between stages:
use std::sync::mpsc::{self, Receiver, Sender};use std::thread;
fn spawn_stage<I, O, F>( input: Receiver<I>, output: Sender<O>, mut process: F,) -> thread::JoinHandle<()>where I: Send + 'static, O: Send + 'static, F: FnMut(I) -> Option<O> + Send + 'static,{ thread::spawn(move || { for item in input { if let Some(result) = process(item) { if output.send(result).is_err() { break; // Downstream closed } } } })}
fn main() { let (source_tx, source_rx) = mpsc::channel(); let (parsed_tx, parsed_rx) = mpsc::channel(); let (validated_tx, validated_rx) = mpsc::channel();
// Parser stage let parser = spawn_stage(source_rx, parsed_tx, |raw: String| { raw.parse::<i32>().ok().map(|n| ParsedData { value: n }) });
// Validator stage let validator = spawn_stage(parsed_rx, validated_tx, |data: ParsedData| { if data.value >= 0 { Some(data) } else { None } });
// Consumer runs in main thread let consumer = thread::spawn(move || { for item in validated_rx { println!("Processed: {:?}", item); } });
// Feed data for item in ["42", "-1", "hello", "100", "0"] { source_tx.send(item.to_string()).unwrap(); }
drop(source_tx);
parser.join().unwrap(); validator.join().unwrap(); consumer.join().unwrap();}
#[derive(Debug)]struct ParsedData { value: i32,}The spawn_stage helper encapsulates the pattern of reading from an input channel, processing items, and forwarding results to an output channel. Returning None from the processing function filters out items, as with the parser rejecting invalid strings and the validator rejecting negative values.
Fan-out and fan-in patterns distribute work across multiple processors. Fan-out sends items to multiple workers for parallel processing. Fan-in collects results from multiple sources into a single stream. The diagram below shows both patterns:
graph TD
subgraph FO["Fan-Out"]
S["Source"] --> W1["Worker 1"]
S --> W2["Worker 2"]
S --> W3["Worker 3"]
end
subgraph FI["Fan-In"]
C["Collector"]
end
W1 --> C
W2 --> C
W3 --> C
[!visual-conversion] Fan-out distributes work; fan-in collects results. Print diagram (PDF 488, printed p. 480) recreated in Mermaid; labels verbatim.
With crossbeam-channel, fan-out happens automatically when multiple receivers clone the same channel. With standard mpsc, distribution requires explicit routing. Fan-in is straightforward with mpsc: multiple senders cloned from the same channel all feed the single receiver.
Actor-like patterns
The actor model structures systems as independent entities that maintain private state and communicate exclusively through messages. Each actor processes messages sequentially, eliminating internal concurrency concerns. Actors can spawn other actors, creating hierarchies of components.
Rust channels enable actor-like patterns without a dedicated actor framework. An actor becomes a thread with a receiver, processing messages in a loop and optionally maintaining state:
use std::sync::mpsc::{self, Sender};use std::thread;
enum CounterMessage { Increment, Decrement, Get(Sender<i64>), Stop,}
struct CounterActor { count: i64,}
impl CounterActor { fn new() -> Self { CounterActor { count: 0 } }
fn handle(&mut self, msg: CounterMessage) -> bool { match msg { CounterMessage::Increment => self.count += 1, CounterMessage::Decrement => self.count -= 1, CounterMessage::Get(reply) => { let _ = reply.send(self.count); } CounterMessage::Stop => return false, } true }}
fn spawn_counter() -> Sender<CounterMessage> { let (sender, receiver) = mpsc::channel();
thread::spawn(move || { let mut actor = CounterActor::new(); for msg in receiver { if !actor.handle(msg) { break; } } });
sender}The CounterActor encapsulates state (count) that only the actor thread can access. External code interacts through messages. The Get variant demonstrates the request-response pattern: the caller includes a one-shot channel where the actor sends the reply.
fn main() { let counter = spawn_counter();
// Increment from multiple threads let mut handles = vec![]; for _ in 0..10 { let counter = counter.clone(); handles.push(thread::spawn(move || { for _ in 0..100 { counter.send(CounterMessage::Increment).unwrap(); } })); }
for handle in handles { handle.join().unwrap(); }
// Query the count let (reply_tx, reply_rx) = mpsc::channel(); counter.send(CounterMessage::Get(reply_tx)).unwrap(); let count = reply_rx.recv().unwrap(); println!("Final count: {}", count); // Should be 1000
counter.send(CounterMessage::Stop).unwrap();}This pattern provides several benefits. State remains private to the actor, impossible to corrupt from outside. Messages are processed sequentially, eliminating races within the actor. The public interface is the message enum, making the actor’s capabilities explicit. Testing becomes straightforward: send messages, check responses.
The overhead of thread-per-actor limits scalability with many actors. For systems requiring thousands of concurrent actors, async runtimes with lightweight tasks provide better efficiency. However, for moderate numbers of actors with significant per-actor state or processing, thread-based actors work well.
Choosing between shared state and message passing
Neither shared state nor message passing universally dominates. Each approach suits different scenarios, and understanding when to use each improves design decisions.
Shared state with locks excels when multiple threads need to read and occasionally write a single piece of data. The cache example from the previous chapter demonstrates this: threads read frequently, write rarely, and the data (a hash map) is inherently centralized. Converting this to message passing would require routing all lookups through a single actor thread, serializing access that could otherwise parallelize.
Message passing excels when threads perform independent work and need only occasional coordination. Pipeline processing, where data flows through stages, maps naturally to channels. Request handling, where each request is independent, benefits from distributing work through channels to a worker pool. Systems where the natural structure involves distinct components with clear communication patterns often become simpler with message passing.
The following considerations guide the choice. Contention patterns matter: shared state with high contention degrades performance as threads wait for locks, while message passing distributes the load across channels. Latency requirements affect the decision: shared state provides immediate access to data, while message passing introduces the latency of channel operations. Complexity of coordination influences the outcome: complex multi-step protocols are often clearer as message sequences than as lock acquisition patterns.
Hybrid approaches are common and appropriate. A system might use message passing between major components while using shared state within a component. A worker pool might share a work queue (using a current queue or channel) while each worker maintains private state using local mutexes. The goal is choosing the right tool for each part of the system.
In my experience, message passing often produces cleaner designs for complex concurrent systems. The explicit nature of channels makes data flow visible. The ownership transfer makes it obvious when data moves between components. The forced serialization within message handlers eliminates categories of subtle bugs. When I find myself struggling with lock ordering or complex synchronization, stepping back to ask whether the design would be simpler with channels often reveals improvements.
Complete example: job processing system
The following example combines the patterns discussed: a job processing system with multiple producers, a dispatcher actor, and a worker pool communicating through channels.
use std::sync::mpsc::{self, Receiver, Sender};use std::thread;use std::time::Duration;
#[derive(Debug, Clone)]struct Job { id: u64, payload: String,}
#[derive(Debug)]struct JobResult { job_id: u64, success: bool, output: String,}
enum DispatcherMessage { Submit(Job), WorkerReady(usize, Sender<Job>), Result(JobResult), Shutdown,}
struct Dispatcher { pending_jobs: Vec<Job>, available_workers: Vec<(usize, Sender<Job>)>, results: Vec<JobResult>,}
impl Dispatcher { fn new() -> Self { Dispatcher { pending_jobs: Vec::new(), available_workers: Vec::new(), results: Vec::new(), } }
fn handle(&mut self, msg: DispatcherMessage) -> bool { match msg { DispatcherMessage::Submit(job) => { if let Some((id, worker)) = self.available_workers.pop() { println!("Dispatching job {} to worker {}", job.id, id); let _ = worker.send(job); } else { println!("Queueing job {}", job.id); self.pending_jobs.push(job); } } DispatcherMessage::WorkerReady(id, sender) => { if let Some(job) = self.pending_jobs.pop() { println!("Dispatching queued job {} to worker {}", job.id, id); let _ = sender.send(job); } else { self.available_workers.push((id, sender)); } } DispatcherMessage::Result(result) => { println!("Job {} completed: {}", result.job_id, result.output); self.results.push(result); } DispatcherMessage::Shutdown => { println!("Dispatcher shutting down with {} results", self.results.len()); return false; } } true }}
fn spawn_dispatcher() -> Sender<DispatcherMessage> { let (sender, receiver) = mpsc::channel();
thread::spawn(move || { let mut dispatcher = Dispatcher::new(); for msg in receiver { if !dispatcher.handle(msg) { break; } } }); sender}
fn spawn_worker( id: usize, dispatcher: Sender<DispatcherMessage>,) -> thread::JoinHandle<()> { thread::spawn(move || { let (job_tx, job_rx): (Sender<Job>, Receiver<Job>) = mpsc::channel();
loop { // Signal ready for work if dispatcher .send(DispatcherMessage::WorkerReady(id, job_tx.clone())) .is_err() { break; }
// Wait for job match job_rx.recv() { Ok(job) => { // Process job thread::sleep(Duration::from_millis(50 + (job.id % 100) * 2)); let result = JobResult { job_id: job.id, success: true, output: format!("Processed '{}' by worker {}", job.payload, id), }; if dispatcher.send(DispatcherMessage::Result(result)).is_err() { break; } } Err(_) => break, } } println!("Worker {} shutting down", id); })}fn main() { let dispatcher = spawn_dispatcher();
// Spawn workers let mut worker_handles = vec![]; for id in 0..4 { worker_handles.push(spawn_worker(id, dispatcher.clone())); }
// Submit jobs from multiple producer threads let mut producer_handles = vec![]; for producer_id in 0..2 { let dispatcher = dispatcher.clone(); producer_handles.push(thread::spawn(move || { for i in 0..10 { let job = Job { id: producer_id * 100 + i, payload: format!("Task from producer {}", producer_id), }; dispatcher.send(DispatcherMessage::Submit(job)).unwrap(); thread::sleep(Duration::from_millis(20)); } })); }
// Wait for producers for handle in producer_handles { handle.join().unwrap(); }
// Allow time for processing thread::sleep(Duration::from_secs(2));
// Shutdown dispatcher.send(DispatcherMessage::Shutdown).unwrap(); thread::sleep(Duration::from_millis(100));}The dispatcher maintains queues of pending jobs and available workers. When a job arrives and a worker is available, immediate dispatch occurs. When workers signal readiness and jobs are pending, queued jobs dispatch. This decoupling allows the system to handle varying loads: during bursts, jobs queue; during lulls, workers wait.
Workers use a dedicated channel to receive jobs, sending this channel to the dispatcher when ready. This pattern avoids the need for a multi-consumer channel while allowing the dispatcher to track which worker receives which job.
The architecture illustrates how message passing creates clear boundaries. The dispatcher’s state is entirely private. Workers have no direct access to the job queue or each other. All coordination happens through the message protocol defined by DispatcherMessage.
Messages Delivered
Channels provide thread-safe communication through ownership transfer. When a thread sends a value, it relinquishes access. When another receives, it gains exclusive ownership. The type system enforces this transfer at compile time.
Standard library channels support multiple producers with a single consumer. The crossbeam-channel crate extends this with multiple consumers, select operations, and additional features.
Synchronous channels provide backpressure by blocking senders when the buffer fills. This prevents unbounded memory growth when producers outpace consumers.
Pipelines structure concurrent systems as stages connected by channels. Data flows through stages, with backpressure propagating naturally through the channel connections.
Actor-like patterns encapsulate state within threads that communicate exclusively through messages. This eliminates internal concurrency concerns and makes the component’s interface explicit through its message types.
Choosing between shared state and message passing depends on access patterns, latency requirements, and coordination complexity. Hybrid approaches often work well, using the appropriate mechanism for each part of a system.
The next chapter explores async Rust, where lightweight tasks replace threads for high-concurrency scenarios. Async code maintains the ownership and message passing patterns while dramatically reducing overhead of concurrent execution.