Sub topic 3
Handling Panics and Send Errors
Assume you know Rust ownership, borrowing, lifetimes, closures, Result, and basic channels. These rules determine how threads communicate failures.
Handling panics and send errors
A spawned thread can panic without immediately stopping the main thread. Its JoinHandle::join method returns a Result. An Err means the thread panicked.
Sending also returns a Result. SendError<T> means the receiver was dropped. The error contains the unsent value, so you can retry or log it.
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
let handle = thread::spawn(move || {
tx.send("work finished").unwrap();
panic!("worker failed afterward");
});
match rx.recv() {
Ok(message) => println!("{message}"),
Err(error) => println!("receive failed: {error}"),
}
if handle.join().is_err() {
println!("worker panicked");
}
}Borrowing local data with scoped threads
thread::spawn usually requires a move closure because the new thread may outlive the current function. thread::scope guarantees that its threads finish before the scope ends. This lets them borrow local variables safely.
use std::thread;
fn main() {
let values = [1, 2, 3, 4];
thread::scope(|scope| {
scope.spawn(|| println!("sum = {}", values.iter().sum::<i32>()));
});
}Bounded channels and backpressure
sync_channel(capacity) creates a bounded channel. Once its buffer is full, send blocks until the receiver removes a value. This backpressure prevents a fast producer from using unlimited memory.
Shared state with `Arc` and `Mutex`
Arc provides shared ownership across threads. Mutex allows only one thread at a time to access protected mutable data. Locking can block, and inconsistent lock order can cause deadlocks.
Building a small worker pool
A worker pool starts several threads, sends jobs through a channel, and gathers results through another. Workers commonly share the receiving end through Arc<Mutex<Receiver<T>>>. Dropping the job sender tells workers that no more jobs exist.
Choosing between messages and shared state
Use message passing when work has clear ownership and events flow between components. Use Arc<Mutex<T>> when threads need coordinated access to one shared value. A worker pool often combines both.
Exercise
What does a failed thread join indicate?
Show answer
The thread terminated by panicking, so handle the returned Err instead of assuming the work succeeded.