When a Rust thread panics, what does unwinding run, what changes under the abort strategy, and what does JoinHandle::join return?
answer
- the hook runs first
- destructors run frame by frame
- stops at the thread boundary
- abort skips Drop entirely
- main panicking means status 101
basics
~20 sBy default a panic runs the panic hook, then unwinds the panicking thread, calling Drop on live values; join on that thread then returns Err. Under abort the hook runs and the whole process dies at once, without destructors.
solid answer
~40 sA panic first calls the panic hook, which by default prints `thread '<name>' panicked at file:line:col:` and the message to stderr. Under the default **unwind** strategy the runtime then walks back up the panicking thread's stack, running `Drop` for every live value in every frame, so guards release, `BufWriter`s flush and temp files get removed, until it reaches the thread's boundary. A panicking spawned thread just ends: `JoinHandle::join` returns `Err(Box<dyn Any + Send>)` carrying the payload, and other threads keep running. If `main` panics, the runtime catches it and the process exits with status 101, ending the other threads. Under the **abort** strategy (`-C panic=abort`, which is what a Cargo profile's `panic` setting passes) the hook still prints, then the process aborts on the spot: no `Drop`, no `join` error, nothing `catch_unwind` can catch.
code
rust · 29 linesuse std::thread;
struct TempFile(&'static str);
impl Drop for TempFile {
fn drop(&mut self) {
println!("drop: removing {}", self.0);
}
}
fn main() {
let worker = thread::spawn(|| {
let _part = TempFile("upload.part");
let chunks: Vec<u8> = Vec::new();
chunks[0] // panics: index out of bounds
});
match worker.join() {
Ok(byte) => println!("worker returned {byte}"),
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!("join: worker panicked: {msg}");
}
}
println!("main: still running");
}go deeper
Know that a panic prints a message and stops the thread, that main panicking ends the program, and that join tells the parent a worker panicked.
Walk through the sequence: hook, then unwinding with Drop in every frame, stopping at the thread root. Contrast abort: hook only, no destructors, no join error, exit by SIGABRT.
Reason about what each strategy loses in production: unflushed buffers and stale lock files under abort, and per-worker isolation and catch_unwind that only exist under unwind.
Weigh unwind against abort for a service: isolation and clean-up versus smaller code and crash-only restarts, and which choice the team's supervision and data-durability story assumes.
## Step one: the panic hook Every panic, whatever triggered it (`panic!`, a failed `unwrap`, an out-of-bounds index), starts the same way: std builds a **payload** (the value describing the panic, usually the message) and calls the **panic hook** on the panicking thread. The default hook prints something like: `thread 'main' panicked at src/main.rs:14:15:` `index out of bounds: the len is 0 but the index is 0` plus a note that `RUST_BACKTRACE=1` shows a backtrace. The hook runs under both strategies; what happens next depends on which panic strategy the binary was built with. ## Step two under unwind: destructors, frame by frame **Unwinding** is the default on most targets. The runtime leaves the current function as if every frame on the panicking thread returned at once: 1. The panic starts and the hook runs. 2. In the innermost frame, every live local that implements `Drop` is dropped, in the usual reverse order. 3. The same happens in the caller's frame, and its caller's, outward. 4. Unwinding stops at a **recovery point**: the root of the thread, or a `std::panic::catch_unwind` call. Because destructors run, RAII keeps working during a panic: a `BufWriter` flushes what it buffered (its `Drop` ignores a failed flush), a lock guard unlocks, a temporary-file guard deletes its file. Unwinding is optimised for the case where it never happens; actually unwinding is comparatively slow, which is one reason panics are not a control-flow tool. ## Where a panic stops: the thread boundary A panic is **per thread**. What the rest of the program sees depends on which thread panicked: - **A spawned thread**: the thread finishes unwinding and ends. Calling `join()` on its `JoinHandle` returns `Err(payload)`, where the payload is a `Box<dyn Any + Send + 'static>` (`std::thread::Result<T>` is that alias). You recover the message by downcasting: a panic whose message needed run-time formatting carries a `String`, a plain literal carries a `&'static str`, so check for both. `std::panic::panic_any` can carry any `Send` value as the payload, which is why code that reads payloads needs a fallback. - **A spawned thread nobody joins**: it still dies alone, its message is printed by the hook, and the program carries on. - **The main thread**: std's runtime catches the panic around `main`, and the process exits with **status 101**. Process exit ends every other thread, finished or not. ## The abort strategy With `-C panic=abort` (the flag a Cargo profile's `panic = "abort"` setting passes to rustc), the hook still runs, and then the process **aborts** immediately. On Unix the process dies from `SIGABRT`, which a shell reports as status 134. | Behaviour | unwind (default) | abort | |---|---|---| | Panic hook prints the message | yes | yes | | `Drop` runs for the thread's live values | yes | no | | Other threads keep running | yes (unless it was `main`) | no, the process is gone | | `join` returns `Err(payload)` | yes | never reached | | `catch_unwind` can catch it | yes | no | | Exit when `main` panics | status 101 | `SIGABRT` | What is lost when destructors are skipped: - data still sitting in a `BufWriter` or any other user-space buffer; - temporary or lock files that a guard would have removed; - any "on drop, tell the coordinator" logic. The operating system still reclaims the process's memory and closes its file descriptors, so abort is not a leak of OS resources, only of the program's own clean-up. ## Why the choice matters Unwinding is what makes per-thread or per-request isolation possible: a worker can die while the server stays up, and a supervisor thread can learn about it through `join`. Abort trades that away for smaller, slightly faster code (the optimiser may assume no frame unwinds) and the guarantee that a bug never leaves a half-handled process running. The profile setting itself, and how crates built with different strategies link, belong to the material on Cargo build profiles; here the point is what each strategy does to `Drop`, `join` and `catch_unwind`.
- Under the default strategy, does a panic in one spawned Rust thread stop the other threads?No. The panic unwinds only the thread it started on; that thread ends and its `JoinHandle::join` returns `Err` with the payload. Other threads keep running. The exception is `main`: when it panics, the runtime exits the process with status 101, and process exit ends every thread.
- Why might a team build a Rust service binary with the abort strategy?Abort gives smaller code, since the optimiser may assume no frame unwinds, and a bug can never leave a half-recovered process running; a supervisor restarts it instead. The cost is that `Drop` clean-up is skipped, `catch_unwind` and `join`-based isolation stop working, and every panic in any thread takes the whole service down.
- How do you read the message out of the payload `join` returns after a panic?Downcast the `Box<dyn Any + Send>`: try `downcast_ref::<String>()` for messages built at run time and `downcast_ref::<&str>()` for plain literals, and fall back to a placeholder for any other payload type, such as one passed to `std::panic::panic_any`.
- With panic = abort, Drop implementations still run before exit.
- A panic in a spawned thread crashes the whole process by default.
- Unwinding skips destructors; only a normal return runs Drop.
- The panic hook does not run when the abort strategy is used.
- catch_unwind still recovers panics in an abort build.