flowchart LR A["Thread A<br/>Sender"] -->|message| C["Channel<br/>bounded queue"] C -->|message| B["Thread B<br/>Receiver"] C -.->|full: sender waits| A C -.->|empty: receiver waits| B
8.8 Message Passing and Channels
8.8.1 Motivation
Shared mutable memory is the root of many bugs. When two threads write to the same location, race conditions emerge. Mutexes prevent races but introduce deadlock risk. Message passing offers a different model: threads do not share state. They send messages to each other through a channel. State that is no longer shared cannot be raced on, so a whole class of bugs goes away with it.
8.8.2 The problem
Shared memory feels natural. Thread A and Thread B both access a queue. Thread A appends. Thread B removes. To avoid races, add a mutex. But now both threads must acquire the mutex, which creates contention, and once a program holds several such locks, the risk of deadlock.
A channel inverts the model. Thread A sends a message (the item). Thread B receives it. The channel handles coordination. The programmer never touches the mutex directly. The sender and receiver see a simple interface: send and receive.
This model matches the dataflow of many programs.
# Shared memory approach
queue <- list()
queue_lock <- new_mutex()
thread_1 <- function() {
for (i in 1:1000) {
lock(queue_lock)
queue[[length(queue) + 1]] <- i
unlock(queue_lock)
}
}
# Message-passing approach
channel <- new_channel()
thread_1 <- function() {
for (i in 1:1000) {
send(channel, i) # No lock needed
}
}8.8.3 Mental model
A channel is a pipe between threads. In the simplest case one thread sends and one receives; Rust’s std::sync::mpsc (“multiple producer, single consumer”) allows many senders and one receiver, and Go’s channels allow many of each. The sender puts messages into the channel. The receiver pulls messages out. The channel handles buffering, blocking, and notification.
With shared memory, both threads touch the same data, and forgetting a lock, or taking the wrong one, causes a race. With channels, each thread touches only its own data: the sender’s outgoing messages and the receiver’s incoming messages. The queue inside the channel is the one shared structure, and the channel’s own synchronization protects it.
Channels can be bounded (a fixed size) or unbounded (no size limit). A bounded channel fills up. When full, the sender must wait until the receiver consumes messages and frees space. This is backpressure. A sender cannot overload a receiver by flooding messages.
8.8.4 Mechanism
Unbounded channels
An unbounded channel is a queue that grows without limit.
send(channel, message):
append message to channel.queue
notify receiver that a message is ready
receive(channel):
if channel.queue is not empty:
return dequeue() from channel.queue
else:
block until a message arrivesThe sender appends and returns immediately. The queue grows. The receiver blocks if the queue is empty. When a message arrives, the receiver wakes.
Unbounded channels are simple but risky. If the sender produces messages faster than the receiver consumes them, the queue grows until memory runs out.
Bounded channels and backpressure
A bounded channel has a fixed size. When the buffer is full, the sender must wait.
send(channel, message):
if channel.queue is full:
block until a slot frees
append message to channel.queue
notify receiver
receive(channel):
if channel.queue is not empty:
result = dequeue() from channel.queue
notify sender (a slot just freed)
return result
else:
block until a message arrivesWhen the receiver consumes, it notifies the sender. The sender wakes and sends if it was blocked.
This is backpressure: the receiver regulates the sender. If the receiver is slow, the sender slows down in tandem. No queue grows unbounded.
Rust’s std::sync::mpsc::channel() creates an unbounded channel. std::sync::mpsc::sync_channel(n) creates a bounded channel with buffer size n. The standard library handles blocking and wakeup. A bound of 0 is allowed and gives a rendezvous channel, where each send waits until a receive takes the message. That is the communication Hoare’s CSP (1978) describes: no buffering, and each side waits for the other.
Ownership transfer
In message passing, ownership of the message transfers from sender to receiver.
data <- data.frame(x = 1:1000, y = rnorm(1000))
send(channel, data)
# After send(), the sender must not access data
# The receiver owns it nowThis prevents a class of bugs: the sender reads the data while the receiver modifies it.
Rust enforces ownership transfer at compile time: send takes the value, and any later use of it fails to compile with error E0382. C relies on programmer discipline. R avoids the question differently. Most of its values behave as copies (copy-on-modify; environments are the main exception), and parallel’s worker processes get their own copy anyway (serialized to a PSOCK worker, copy-on-write pages in a forked one), so a receiver’s changes never reach the sender’s object.
8.8.5 A simple example
Two threads communicate via a channel.
channel = new_channel(size = 10)
thread_1():
for i in 1 to 100:
send(channel, i * 2) // sender, no lock
close(channel)
thread_2():
while message = receive(channel):
print(message) // receiver, no lockThread 1 sends 100 messages (2, 4, 6, …, 200). Thread 2 receives and prints. The channel buffers up to 10 messages. If Thread 1 is faster, it blocks at send() until Thread 2 consumes. Neither thread takes a lock in its own code.
8.8.6 Strengths
Avoiding races: Shared memory requires discipline to protect every access. With channels, the protection sits in one place: if threads communicate only through the channel, the channel is the only thing that needs synchronization. That holds only as long as the messages do not carry shared memory with them. A Go program can send a pointer and race on what it points to; Rust lets a message cross threads only if its type is Send, so shared data travels as something like Arc<Mutex<T>> and never as a bare Rc.
Composability: Two modules can communicate via channels without knowing each other’s internal state. Module A sends to a channel. Module B receives. They do not share memory.
Easier deadlock reasoning: A straight chain of stages in which data flows one way through channels has no cycle of waits, so channel waits alone cannot deadlock it. A stage that reads two bounded channels in a fixed order can still deadlock with its sender. Deadlock also returns when the communication graph has a cycle: thread A blocks sending to B on a full channel while B blocks sending to A on another full channel, or each waits to receive from the other.
8.8.7 The costs
Copying: Every message is moved or copied into the channel’s buffer. Within one process this can be cheap: a Rust Vec moves as its three-word header, and its elements stay where they are. Between processes, as with R’s parallel workers, the whole value is serialized and copied, so large messages mean large copies.
Latency: A message must be enqueued, the receiver may need to be woken, and then it must be dequeued. This path is slower than a shared pointer dereference.
Complexity: Channels introduce a new abstraction. Synchronizing code is still hard, just in a different way. A receiver can wait forever for a message that never comes (deadlock shifted, not eliminated).
8.8.8 When to use channels
Channels fit producer-consumer patterns. A producer thread generates work. A consumer thread processes it. A channel connects them. This pattern is common in streaming systems, worker pools, and data pipelines.
Channels do not fit fine-grained data sharing. If two threads read and write the same hash table at a high rate, shared memory with mutexes is usually faster, because each lookup is cheaper than a round trip through a channel to a thread that owns the table.
8.8.9 Alternatives
Actor model: Instead of channels, use actors. Each actor owns data and receives messages. Actors process one message at a time. This prevents races within an actor. External actors never see the actor’s state. This model fits Erlang and some Rust frameworks.
Immutable shared data: Threads share immutable data pointers without locks. Mutation is not allowed. New versions are copied. This fits functional languages and Rust’s Arc<T>.
Read-write locks: A compromise between full sharing and channels. Many threads read the same data. One writer at a time. Readers do not block each other.
8.8.10 Comparison
| Approach | Pros | Cons | Best for |
|---|---|---|---|
| Shared memory + mutex | Direct access, standard | Easy to race, deadlock risk | Coarse-grained state |
| Channels | No shared state to race on, natural flow | Copying cost, new abstraction | Producer-consumer, pipelines |
| Immutable + copy | No races, no locks | Always copying, memory cost | Functional patterns |
| Read-write locks | Readers scale, one writer | More complex than mutex | Heavy-read workloads |
A bounded channel between two threads. Sender blocks if the buffer is full, preventing memory overload. Receiver blocks if empty, waiting for work.
Further reading
- Rust documentation for std::sync::mpsc: https://doc.rust-lang.org/std/sync/mpsc/
- “Communicating Sequential Processes” by C.A.R. Hoare, Communications of the ACM 21(8), 666-677 (1978). Processes communicate by synchronous input and output commands that name each other, with no buffering; section 7.3 sketches named ports and channels as an alternative. The Go FAQ places Go’s channels in the CSP family tree. https://dl.acm.org/doi/10.1145/359576.359585
- “Go Concurrency Patterns: Pipelines and cancellation” by Sameer Ajmani, The Go Blog (2014). Builds pipelines from goroutines and channels. https://go.dev/blog/pipelines
- Erlang documentation, “Concurrent Programming”: spawning processes and passing messages between them. https://www.erlang.org/doc/system/conc_prog.html
Where this appears
- r-in-rust (rrs) rrs could pass messages between interpreter threads with Rust’s standard std::sync::mpsc channels.