Threads and Message Passing
Rust's approach to concurrency goes by the slogan fearless concurrency. Ownership and the type checker rule out data races at compile time, so you can ship threaded code without the usual sweating.
Creating Threads
Rust's standard library provides OS threads via std::thread::spawn:
use std::thread;use std::time::Duration;
fn main() { let handle = thread::spawn(|| { for i in 1..=5 { println!("Thread: {}", i); thread::sleep(Duration::from_millis(10)); } });
for i in 1..=5 { println!("Main: {}", i); thread::sleep(Duration::from_millis(10)); }
handle.join().unwrap();}thread::spawn takes a closure and hands back a JoinHandle. .join() blocks until the thread wraps up, and .unwrap() re-raises any panic that happened inside.
Move Closures
Closures borrow from their environment by default. Threads, though, demand 'static — they might outlive whoever spawned them. The fix is move, which hands ownership into the thread:
use std::thread;
fn main() { let data = vec![1, 2, 3, 4, 5];
// This would not compile without `move`: let handle = thread::spawn(move || { let sum: i32 = data.iter().sum(); println!("Sum: {}", sum); });
// data is no longer accessible here - ownership moved to the thread // println!("{:?}", data); // ERROR: use of moved value
handle.join().unwrap();}The move keyword shifts ownership of captured variables into the closure. That's the mechanism behind Rust's data-race guarantee: once the main thread loses ownership, it can't poke at the data alongside the spawned thread. The compiler bakes this in long before runtime.
Delete move from the example above. Does it still compile?
No. The compiler rejects it with error[E0373]: closure may outlive the current function, but it borrows data, which is owned by the current function, and its suggested fix is to add move. thread::spawn requires a 'static closure, and a borrow of a local in main can't promise that: as far as the type system knows, the thread might still be running after data is gone.
Channels: Message Passing
Rust's std::sync::mpsc (multiple producer, single consumer) module provides channels for thread communication:
use std::sync::mpsc;use std::thread;
fn main() { let (tx, rx) = mpsc::channel();
thread::spawn(move || { let messages = vec!["hello", "from", "the", "thread"]; for msg in messages { tx.send(msg).unwrap(); thread::sleep(std::time::Duration::from_millis(100)); } });
for received in rx { println!("Got: {}", received); }}A channel has two halves: tx (transmitter) and rx (receiver). Drop every sender and the receiver's iterator finishes — termination falls out for free.
The runner gives you no spare threads, but a channel doesn't care which thread holds each end, so one thread can play both parts. That's enough to see the shutdown rule in action, plus the back-pressure of a bounded sync_channel, which you'll meet properly further down.
Multiple Producers
Clone the sender to share it across threads:
use std::sync::mpsc;use std::thread;
fn main() { let (tx, rx) = mpsc::channel(); let tx2 = tx.clone();
thread::spawn(move || { for i in 0..5 { tx.send(format!("Thread A: {}", i)).unwrap(); } });
thread::spawn(move || { for i in 0..5 { tx2.send(format!("Thread B: {}", i)).unwrap(); } });
for msg in rx { println!("{}", msg); }}Channels vs Shared State
Go made the slogan famous: "Do not communicate by sharing memory; share memory by communicating." Rust lets you do either, but channels carry their own advantages:
Use channels when:
- Transferring ownership of data between threads
- Implementing pipelines or actor patterns
- You want clear unidirectional data flow
Use shared state when:
- Multiple threads need read access to the same data
- You need to update data in place
- The overhead of copying data through channels is too high
Typed Channels
Channels carry a type. Send anything else and the compiler stops you cold:
use std::sync::mpsc;
enum WorkItem { Task(String), Shutdown,}
fn main() { let (tx, rx) = mpsc::channel::<WorkItem>();
// Workers receive typed messages let handle = std::thread::spawn(move || { loop { match rx.recv().unwrap() { WorkItem::Task(name) => println!("Processing: {}", name), WorkItem::Shutdown => { println!("Shutting down"); break; } } } });
tx.send(WorkItem::Task("compile".to_string())).unwrap(); tx.send(WorkItem::Task("test".to_string())).unwrap(); tx.send(WorkItem::Shutdown).unwrap();
handle.join().unwrap();}Synchronous Channels
mpsc::sync_channel creates a bounded channel that blocks the sender when full:
let (tx, rx) = mpsc::sync_channel::<i32>(5); // Buffer size 5
// If buffer is full, tx.send() blocks until space is available// This provides natural back-pressureScoped Threads (Rust 1.63+)
std::thread::scope lets threads borrow from the parent's stack without move:
use std::thread;
fn main() { let data = vec![1, 2, 3, 4, 5]; let mut results = vec![];
thread::scope(|s| { // Can borrow `data` without move because the scope // guarantees all threads finish before scope exits let h1 = s.spawn(|| data[..3].iter().sum::<i32>()); let h2 = s.spawn(|| data[3..].iter().sum::<i32>());
results.push(h1.join().unwrap()); results.push(h2.join().unwrap()); });
let total: i32 = results.iter().sum(); println!("Total: {}", total); // 15}Scoped threads ditch the ergonomic tax of move and Arc for every shared reference. The scope guarantees all spawned threads finish before it exits, so plain borrows are sound.
Error Handling Across Threads
Threads can communicate errors through their return values or through channels:
use std::thread;
fn main() { let handle = thread::spawn(|| -> Result<i32, String> { // Simulate work that might fail let value = compute()?; Ok(value) });
match handle.join() { Ok(Ok(value)) => println!("Result: {}", value), Ok(Err(e)) => eprintln!("Thread returned error: {}", e), Err(_) => eprintln!("Thread panicked"), }}The outer Result from join() tells you whether the thread panicked. The inner Result carries whatever the thread chose to return.
Challenges
Create two threads that each send 5 numbers through a channel to the main thread. The main thread should collect all 10 numbers, sort them, and print the sum.