Spawn new thread on panic

As I was writing this thread, I came up with a follow up question, which is:

Is it possible to spawn a replacement thread when one panics, always keeping the total number of threads below a defined limit?

My specific application is a web server, but I could see it for other longer running programs where rather than killing the whole app or operating with one less thread, you log the panic, and resume handling requests while restoring the total number of threads you had before.

This would allow for a more fault tolerant piece of software that can recover from bad data or actions by its users that would otherwise cause a hard crash.

Admittedly I am relatively new to multi-threaded programming so I probably have some fundamental misunderstandings here.

However, if this is possible in rust, I would be very interested!

Thanks

Possible? Yes, for sure... given that your panic actually unwinds (panics are also allowed to abort the process).

Idiomatic? No, not really. In Rust, it is generally discouraged to use panics as a form of recoverable error handling. It is necessary in some cases, but most of the time you're better off actually handling the "expected" errors by returning Results and stuff like that.

Note that you can return Result from a thread too, so instead of panicking, you'd just return Err(...) or ?.
Then on the joining side, you can unwrap the outer Result (for bugs in your code), and handle the inner Result by restarting the thread.

1 Like

The general approach used by crates for webservers is to catch and stop panics before they stop a thread, so there's no need to spawn new ones to compensate.

3 Likes