4 ms·
Just don’t put unwrap in library code, please. Not if it can possibly happen, bearing in mind that you can make mistakes. I like my background threads to be in
by Filligree 1y ago
Just don’t put unwrap in library code, please. Not if it can possibly happen, bearing in mind that you can make mistakes.
I like my background threads to be infallible. If they panic, then chances are nothing will notice and the rest of the program will solely seize up.
I might have agreed with more of this article if panics actually crashed the program, but in multithreaded Rust that’s rarely the case.
- Zambyte 1y ago> I might have agreed with more of this article if panics actually crashed the program, but in multithreaded Rust that’s rarely the case. Why is that?
- littlestymaar 1y agoIf you don't join the threads a panic get stopped at thread boundaries (unless you have taken a lock when the panic happens, in which case the lock is poisoned and attempting to lock it again will return an error. Error that will most likely trigger a further panic since you usually write something like let mutex_guard= mutex.lock().expect("poisoned lock");
- tayo42 1y agoI don't think this is uniquely a rust thing. I had a multi threaded python app that had uncaught exceptions kill threads and the whole thing stopped working but kept running along
- jerf 1y agoThe more threads you have doing something, the higher the probability you have at least one thread doing something that you don't want to have interrupted just because some other thread, somewhere, failed. The lock case mentioned by littlestymaar is an important "program correctness" consideration, but also consider something like a instant message or chat server like Slack. You don't want the entire server with thousands of connections to crash just because one thread somewhere crashed. It's expensive to reconnect the system after that. Also, the more threads you are running, the higher the odds get that one of them will panic somewhere, somehow. The numbers start adding up. Each of these two effects conspire to make the other one worse as you scale up.
- goku12 1y agoI believe that your argument is implied in the article. Errors that are expected at runtime must be handled (preferably in the application code), instead of unwrapping it. If the thread does panic due to an unwrap (even without crashing the main thread), it's a logical error in the library that must be resolved before the public/production release. There are cases where unwrap may be necessary even within a library. Burntsushi's own regex crate has an example of this. You get a Result when you construct a regex - which is reasonable if the regex is parsed at runtime. But I don't see any reason to not use unwrap, if the expression is a static string within the library source.