Threads and communication.
Understand independent work, ownership transfer, and message passing.
The idea behind the syntax.
Threads can make progress independently, sometimes on different CPU cores. That introduces a coordination problem: what data belongs to which thread, and when is a result ready? Rust's ownership rules still apply. Moving a value into a spawned thread makes the transfer explicit; the old scope cannot keep using an owned value as if nothing changed.
A channel sends messages from a producer to a consumer. Sending usually transfers ownership of the message, so the receiver can process it without a second writer changing the same value. Channels do not remove the need to think about ordering, shutdown, or backpressure. A receiver may block while waiting, and a sender may discover that the other end has been dropped.
What Rust is checking.
A join handle lets one thread wait for another to finish and observe its result or panic. Dropping a handle is not the same as stopping the thread. If a worker must shut down, the program needs an explicit signal and a plan for outstanding messages. The shape of those messages can be an enum, giving each command a clear payload.
Concurrency is not automatically parallel speedup. Starting threads has overhead, and contention or I/O can dominate the work. Read a threaded example by marking which values move into each closure, what crosses the channel, and where the main thread waits. That ownership map reveals both the safety story and the program's possible execution orders.
See the rule in context.
Each example isolates one part of the model. Follow the bindings, types, ownership transfers, and possible outcomes line by line.
Threads, move & join
std::thread::spawn runs a closure on another operating-system thread. Spawned closures generally need owned or static data because the new thread may outlive the caller’s current stack frame. A move closure can transfer a vector into the thread. join waits for termination and returns a Result because the thread may panic. Thread scheduling is nondeterministic, so do not depend on print ordering. For borrowed work that must finish before a scope exits, scoped threads provide a useful alternative.
use std::thread;
fn main() {
let values = vec![2, 4, 6];
let worker = thread::spawn(move || values.into_iter().sum::<i32>());
let total = worker.join().expect("worker completed");
println!("total={total}");
}total=12
- move transfers the vector into the closure.
- The worker owns the values it consumes.
- join returns the final sum and synchronizes completion.
The boundary: Dropping a JoinHandle detaches its thread; it does not cancel or join it. Plan shutdown explicitly.
Channels & message ownership
A channel transfers messages between a sender and a receiver. std::sync::mpsc provides multiple producers and one receiver; sending an owned value moves it. The receiving iterator ends when every sender is dropped, so keeping an unused sender alive can accidentally block shutdown. sync_channel adds bounded capacity and backpressure, while channel is unbounded. Choose capacity and overload behavior deliberately rather than letting a fast producer grow memory without limit.
use std::{sync::mpsc, thread};
fn main() {
let (tx, rx) = mpsc::sync_channel(2);
let worker = thread::spawn(move || {
for n in 1..=3 {
tx.send(n).unwrap();
}
});
let total: i32 = rx.iter().sum();
worker.join().unwrap();
println!("total={total}");
}total=6
- The bounded channel can hold at most two waiting messages.
- The producer drops its sender when it returns.
- The receiver’s iterator finishes after queued messages drain and all senders are gone.
The boundary: A channel does not solve every deadlock: waiting for a worker before draining a full bounded channel can block both sides.
Keep this model.
Message passing makes ownership transfer a communication protocol. Thread safety still requires clear lifecycle and ordering decisions.