In Rust, how does a worker thread's panic surface differently under `thread::spawn` and under `thread::scope`, and how do you read the panic message?
answer
- unwinding stays in one thread
- Err from join, or nothing
- an unjoined scoped panic re-panics
- downcast to &str and String
basics
~20 sA panic unwinds only its own thread. Under thread::spawn it reaches you as Err(payload) from join, or not at all. Under thread::scope an explicit join also gives Err, but an unjoined panic makes scope panic once all threads end.
solid answer
~40 sUnder the default unwind strategy a panic unwinds only the thread it happened in; the panic hook prints `thread '<name>' panicked at ...` to stderr and the rest of the program keeps running. With `thread::spawn`, the failure reaches you only through `JoinHandle::join`, which returns `Err(Box<dyn Any + Send>)`; a dropped handle means the panic is visible in stderr and nowhere else. With `thread::scope`, joining a `ScopedJoinHandle` by hand gives the same `Err` and the scope carries on, but if the panicked thread was left to the automatic join, `scope` waits for every other thread and then panics on the caller with "a scoped thread panicked", without the original payload. To read the message, `downcast_ref::<&str>()` and `downcast_ref::<String>()` on the payload, trying both.
code
rust · 30 linesuse std::thread;
fn main() {
// A thread::spawn worker: the panic comes back as Err from join.
let h = thread::spawn(|| -> usize { panic!("bad record at offset {}", 4096) });
match h.join() {
Ok(n) => println!("count {n}"),
Err(payload) => {
let msg = payload
.downcast_ref::<String>()
.map(String::as_str)
.or_else(|| payload.downcast_ref::<&str>().copied())
.unwrap_or("non-string payload");
println!("worker failed: {msg}");
}
}
// A scoped worker joined by hand: the scope itself does not panic.
let r = thread::scope(|s| s.spawn(|| panic!("chunk 2")).join().is_err());
println!("joined by hand, err = {r}");
// A scoped worker left to auto-join: scope panics after every thread ends.
let outcome = std::panic::catch_unwind(|| {
thread::scope(|s| {
s.spawn(|| panic!("chunk 3"));
s.spawn(|| println!("sibling still finishes"));
});
});
println!("auto-joined, scope panicked = {}", outcome.is_err());
}go deeper
Recall that a panic unwinds only its own thread and that join returns Err with the payload, so an unjoined worker can fail without the main thread noticing.
Explain the payload type, Box<dyn Any + Send>, and downcasting to &str and String, plus the difference between joining a scoped handle and relying on the automatic join.
Diagnose a tool that reported success with missing output: an unjoined worker panicked. Show how per-worker joins, thread names and explicit failure handling make that impossible.
Set the policy for worker failure: whether one panic aborts the whole batch, how partial results are marked or discarded, and how panics become logs and alerts rather than stderr lines.
## A panic belongs to one thread With the default `panic = "unwind"` strategy, a `panic!` unwinds the stack of the thread it happened in: destructors on that stack run, and the thread ends. Other threads are not interrupted. Before unwinding, the panic hook prints a line such as `thread 'compactor-2' panicked at src/main.rs:5:10:` followed by the message, using the thread's name if it has one. How unwinding and the abort strategy work in general is covered in the lesson on panics; what matters here is how the failure reaches the code that started the thread. ## Under `thread::spawn`: an `Err` from `join`, or nothing `JoinHandle::join` returns `std::thread::Result<T>`, an alias for `Result<T, Box<dyn Any + Send + 'static>>`. A panicked worker produces `Err(payload)`. Two consequences follow: - **Joined**: you choose. `.join().expect("worker panicked")` re-panics on the caller; a `match` can log the message and continue with partial results. - **Not joined**: the panic is printed to stderr by the hook, and that is all. `main` never learns that a worker died, which is how a log compactor silently writes a file missing one quarter of its records. If the worker held a `std::sync::Mutex` when it panicked, the lock is poisoned too; that mechanism belongs to the lesson on mutexes. ## Under `thread::scope`: it depends on whether you joined Scoped threads add a rule, because `scope` must never return while a thread could still be running, and it must not lose a failure silently either: | Situation | What you see | |---|---| | `spawn`ed thread panics, handle joined | `join` returns `Err(payload)` | | `spawn`ed thread panics, handle dropped | message on stderr only | | scoped thread panics, `ScopedJoinHandle::join` called | `join` returns `Err(payload)`; scope does not panic for it | | scoped thread panics, left to the automatic join | `scope` waits for **all** threads, then panics with "a scoped thread panicked" | | the scope closure itself panics | `scope` still waits for all threads, then resumes that panic | The library implements this with a flag: when a scoped thread ends with a panic result that nobody took, it records "a thread panicked", and after the running-thread count reaches zero `scope` checks the flag and panics. Three details matter in review: 1. **The original payload is not carried** into the scope's panic. If you need the message, join the handle yourself before the scope ends; the docs give exactly that advice. 2. **Siblings are not cancelled.** A panic in one scoped thread does not stop the others; `scope` waits for them to finish normally. Stopping early needs your own signal, such as a shared flag the workers check. 3. `thread::scope` returns `T`, not a `Result`. The ecosystem's older crossbeam `scope` returned `thread::Result<R>`, which is where the idea of getting an `Err` back from the scope comes from. ## Reading the payload The payload is a `Box<dyn Any + Send>`, so you downcast it. It has no `Display` impl, and its `Debug` output is just `Any { .. }`: - `payload.downcast_ref::<&str>()` matches a message that is fixed at compile time, such as `panic!("disk full")`. On rustc 1.99.1, `panic!("n = {}", 3)` with a constant argument also produced a `&'static str`, because the formatting was resolved at compile time. - `payload.downcast_ref::<String>()` matches a message formatted at run time, such as `panic!("bad offset {offset}")` with a runtime variable. - `std::panic::panic_any(value)` can carry any `Send + 'static` type, so neither downcast is guaranteed to succeed; keep a fallback like "non-string payload". Because the exact type depends on how the message was built, robust code tries both downcasts rather than guessing. ## What to do in a worker-based tool - Join every handle and turn `Err(payload)` into a logged message with the worker's name and chunk id. - In a scope, join handles explicitly when you want per-worker error reporting; rely on the automatic join only when any panic should abort the whole operation. - Name threads with `thread::Builder::name` so the hook's line says which worker failed. - Treat a worker panic as a failed result: do not write output assembled from the surviving workers as if it were complete. ## A note on `catch_unwind` inside the worker An alternative is to catch the panic inside the worker with `std::panic::catch_unwind` and return a `Result` through `join`, so every worker reports success or failure in the same type. That works only under the unwind strategy and is covered with panics; for thread workers, matching on the `Err` from `join` already gives you the payload without wrapping each closure.
- When `thread::scope` panics because a scoped thread panicked, can you recover the worker's message from that panic?No. The scope raises a new panic with the fixed message "a scoped thread panicked"; the worker's payload was dropped with its unjoined result. To keep the message, call `ScopedJoinHandle::join` inside the scope and handle the `Err(payload)` there.
- Does a panic in one scoped thread stop its sibling threads?No. std has no thread cancellation; the panicking thread unwinds and ends, while siblings run to completion and `scope` waits for them. To stop early, give workers a shared stop signal, for example an atomic flag they check between records, and set it when a failure is seen.
- Why can `payload.downcast_ref::<String>()` return `None` for a panic with a message?Because the payload type depends on how the message was produced. A message known at compile time, such as `panic!("disk full")`, is stored as a `&'static str`, so only `downcast_ref::<&str>()` matches; a message formatted at run time is a `String`. Try both, and keep a fallback for `panic_any` payloads.
- A panic in any spawned thread always terminates the whole process.
- thread::scope returns Err when one of its threads panics.
- The scope's own panic re-throws the worker's original payload.
- When one scoped thread panics, std cancels the sibling threads.
- The payload of panic! is always a String you can print directly.