36
top 30 comments
sorted by: hot top new old
[-] JATothrim_v2@programming.dev 2 points 1 day ago

This post annoyed me enough to answer. A robust mutex: a futex shared by processes. If a process crashes while holding a robust mutex, it's possible to recover from such a situation.

The rust people are basically trying to reinvent a robust mutex. If your thread crashes, it should bring down the entire process, pronto. If it should not, use a process.

Why are they not just storing a extra bit in the futex word, is beoynd me.

[-] TehPers@beehaw.org 2 points 1 day ago

If your thread crashes, it should bring down the entire process, pronto. If it should not, use a process.

This highly depends on the environment. Rust is used in a lot of places where you don't have the option to spawn multiple processes. Even in environments where spawning is an option, it's not often desirable to take down the whole service when one panic occurs.

It also has nothing to do with mutex poisoning. In fact, if this were the case, you would not need poisoning at all because the process could terminate before the lock is released.

[-] JATothrim_v2@programming.dev 1 points 1 day ago

I do know that in embedded programming you have very little head room.

In fact, if this were the case, you would not need poisoning at all because the process could terminate before the lock is released.

That's precisely when you need a robust mutex. The process that held the mutex is now dead. Trying to lock the mutex gives you the bit that the state supposedly protected by the mutex is now invalid.

[-] SorteKanin@feddit.dk 1 points 1 day ago

If a process crashes while holding a robust mutex, it’s possible to recover from such a situation.

But that's the whole point of poisoning too. If a different thread crashed and the mutex is poisoned, you can recover in a different thread. Most applications choose not to recover and chooses to just panic again, but you can choose to recover.

[-] xthexder@l.sw0.com 7 points 2 days ago

In my opinion, catching a panic is a mistake in the first place. They're meant to be unrecoverable anyway, so if you want the program to keep running, use Result types or return errors some other way.

[-] sgued@programming.dev 1 points 1 day ago

There are valid reasons to want to catch panics. The N°1 usage of catch_panic are testing tools. But even then, in a low-stakes web server for example, it can make sense to catch panics to return a 500, and it's unlikely that a panic would lead to corrupted state outside of a poisonned mutex, so keeping running can make sense.

[-] SorteKanin@feddit.dk 4 points 2 days ago

Mutex poisoning isn't really about catching panics. Mutex poisoning happens without any relation to catch_unwind.

The thing with mutex poisoning is that it is multi-threaded. One thread holds the mutex and panics. It does not catch the panic, the thread simply dies and releases the lock while unwinding. That marks the mutex as poisoned.

Another thread then tries to get the mutex and sees the poison error. This other thread is still alive since panics do not propogate among all threads. Panics only kill the thread the panic occurs on.

[-] xthexder@l.sw0.com 2 points 2 days ago* (last edited 2 days ago)

I guess I would have thought panic would trigger other threads to abort as well. Admittedly I haven't really done any multithreading in Rust. I was thinking it was more like exit(status) in C/C++ that immediately terminated the entire process. Exception unrolling in general I feel is something that should be avoided if you care at all about error conditions.

If panics are isolated to one thread, then I guess mutex poisoning is a better default error case than a deadlock where the process never exits. An entirely independent thread might still be unaware the rest of the program has crashed though.

[-] SorteKanin@feddit.dk 2 points 2 days ago

Panics in Rust default to stack unwinding, which I believe is similar to how exceptions work in C++. I don't believe an unhandled exception in C++ kills other threads either? Could be wrong.

Panics can also be configured to instead abort the process immediately, which is the exit(status) way. Obviously with that solution you can never observe a poisoned mutex so you would never need a poisoning mutex in that situation anyway.

[-] fruitcantfly@programming.dev 3 points 2 days ago* (last edited 1 day ago)

I don’t believe an unhandled exception in C++ kills other threads either? Could be wrong.

An unhandled exception in C++ causes the program to call std::terminate, which calls std::abort by default and brings down the entire program. I don't think there's a way to prevent an unhandled exception from doing that without causing nasal demons, but I could likewise be wrong. According to the standard, regarding the function function called by std::terminate:

A std::terminate_handler shall terminate execution of the program without returning to the caller, otherwise the behavior is undefined.

A quick check suggests that GCC's std::terminate calls std::abort if your terminate handler does not, but I don't know if that applies to other implementations.

EDIT: If anyone else is curious, here is the GCC implementation:

void
__cxxabiv1::__terminate (std::terminate_handler handler) throw ()
{
  __try
    {
      handler ();
      std::abort ();
    }
  __catch(...)
    { std::abort (); }
}

The LLVM version does the same thing.

[-] kubica@fedia.io 1 points 2 days ago

I don't quite get it, why should a mutex that was released because the thread panicked stay as it everthing is going just fine?

[-] SorteKanin@feddit.dk 7 points 2 days ago* (last edited 2 days ago)

Because many (some would say most) use cases don't have an actual window in their critical section where

  1. The invariant the Mutex protects is broken.
  2. There is a possibility of a panic.

Usually that's simply not the case. You only need poisoning if you have the mutex unlocked and you are temporarily breaking its invariant before reconstructing the invariant and there's a possibility of panic before that reconstruction occurs.

Even if your use case is like that, there's a fairly good argument that mutex.lock() should just automatically panic and should not require mutex.lock().unwrap(), because most applications would never try to handle a poisoning error. They would just propogate the panic and try to shut down ASAP. If you really wanted to handle that poison, we could just have a different method for that, like mutex.try_poison_lock() or whatever. But the standard library unfortunately chose that mutex.lock() should return a poison error.

[-] kubica@fedia.io 5 points 2 days ago

Ok, that goes more straight to the point than the article. I see the point now.

[-] SorteKanin@feddit.dk 3 points 2 days ago

Mutex poisoning has been a recurring topic of debate in the Rust community so I think the article probably comes at it from a bit of an in-group perspective where it expects the reader to already have a bit of this context :)

[-] orclev@lemmy.world 2 points 2 days ago

It's a good article and I agree, poisoning is a niche use case and shouldn't be the default. That said it should document explicitly that it doesn't handle panics in the critical section and that if you need that you should use a variant that does support poisoning. Basically the opposite of the situation as it currently exists where the default is poison with a note saying if you don't need it use the non-poisoning (nightly only) version.

[-] BB_C@programming.dev 0 points 2 days ago
  1. The only real argument for not poisoning is "performance" (at the expense of safety). Provide a real-world use-case where you think poisoning is supposedly the bottleneck, and I will ^(try^ ^to)^ show you that it isn't.

  2. I like how everyone is pretending writing your own extension trait is not a thing, where you can just add methods like panicking-lock() (with whatever short name you like), but also for backed-off lock (with try_lock() which is one atomic op and time-outs).

[-] TehPers@beehaw.org 2 points 1 day ago

I'm having trouble finding any popular alternative implementations of Mutex that support poisoning. parking_lot, tokio, and futures all have non-poisoning (possibly async) mutexes.

In fact, there's almost no argument for requiring poisoning. There are some fringe cases where poisoning is useful, and in those cases, you could just as easily create a Poisoning<T> pointer that implements it.

As the article says, no other built-in pointer type in Rust support poisoning, yet the same "invalid state" argument can be made for all of them. A &mut T can become temporarily "invalid" (in a sound manner) during a critical block that panics, for example. That pointer could be mutating data that's eventually dropped during unwinding, does not hold its invariants at this time, and triggers a Drop impl that's unsound as a result. At the end of the day, the correct way to handle this is to somehow either fix the state during unwinding so that it no longer violates an invariant, or mark it as poisoned, regardless of pointer type.

The only real argument for poisoning by default is because it already is the default. It's a strong argument of course (it would likely be a breaking change to remove it), but it's not a very solid argument for why it should be a default to begin with.

[-] BB_C@programming.dev 1 points 1 day ago

I’m having trouble finding any popular alternative implementations of Mutex that support poisoning.

https://docs.rs/saa/5.6.4/saa/lock/struct.Lock.html

[-] TehPers@beehaw.org 1 points 1 day ago* (last edited 1 day ago)

I'm confused by this. saa::Lock does support poisoning, but it appears to be manual. You need to both manually mark it as poisoned via lock.poison_lock() and manually check if it's poisoned with the return value from locking. You can easily ignore poisoning entirely - it's actually more opt-in rather than forced on you. So sure this supports poisoning, but it's not forced on you like std::sync::Mutex, and saa::Lock isn't anything close to a complete Mutex alternative anyway.

It seems to support lock_api apparently (presumably as the locking implementations behind it?), but lock_api::Mutex doesn't appear to support poisoning at all.

[-] SorteKanin@feddit.dk 4 points 2 days ago

I don't think performance is the bottleneck. The real reason to not use poisoning mutexes is convenience and developer experience. The standard library should take such considerations heavily into account. A rare use case such as poisoning being requried should not be the default for mutexes in the standard library.

[-] BB_C@programming.dev 0 points 2 days ago

The real reason to not use poisoning mutexes is convenience and developer experience. The standard library should take such considerations heavily into account. A rare use case such as poisoning being required should not be the default for mutexes in the standard library.

What does that even mean?

The interface concerns are as trivial as it gets:

#![feature(nonpoison_mutex)]
#![feature(sync_nonpoison)]

use std::sync::Mutex as PMutex;
use std::sync::nonpoison::Mutex as NoPMutex;

trait LockExt<'a> {
    type Guard;
    fn l(&'a self) -> Self::Guard;
}

impl<'a, T: 'a> LockExt<'a> for PMutex<T> {
    type Guard = std::sync::MutexGuard<'a, T>;
    fn l(&'a self) -> Self::Guard {
       self.lock().expect("non-poisoned") 
    }
}

impl<'a, T: 'a> LockExt<'a> for NoPMutex<T> {
    type Guard = std::sync::nonpoison::MutexGuard<'a, T>;
    fn l(&'a self) -> Self::Guard {
       self.lock() 
    }
}

fn main() {
    let m_p = PMutex::new(false);
    let m_no_p = NoPMutex::new(false);
    *m_p.l() = true;
    *m_no_p.l() = true;
    dbg!(*m_p.l());
    dbg!(*m_no_p.l());
}

This is basically is the one thing that shouldn't consume any mind tokens when it comes to synchronization primitive choice.

[-] SorteKanin@feddit.dk 1 points 2 days ago

I'm not really sure what you're trying to say here. Are you saying that this is not a problem and everyone should just add this LockExt trait to all their code bases that uses Mutexes? Or..?

[-] BB_C@programming.dev 2 points 2 days ago

Every non-trivial code-base already has a utils module (sometimes a whole crate even) containing, in part, extension traits (and sometimes macros) to make some usages of some types nicer, in a way that is specific to the codebase (even in this case, a codebase might want a debug or trace log message for example, alongside the panic).

It's a part of the language for a reason. It provides full idiomacity. And this is not limited to (poisoned or otherwise) synchronization primitives.

Talking about a method returning a Result like it's a big deal must be some sort of splitting-hairs maxxing.

And btw, as it just happens, such traits actually already exist, in a crate that is well-known to the ecosystem.

[-] SorteKanin@feddit.dk 1 points 2 days ago

in a way that is specific to the codebase

Well I would say this is not at all specific to the codebase - as I said above, it applies to basically all code bases that use mutexes, since poisoning is so rarely relevant.

These two statements are kind of strange to me:

Talking about a method returning a Result like it’s a big deal must be some sort of splitting-hairs maxxing.

and

And btw, as it just happens, such traits actually already exist, in a crate that is well-known to the ecosystem.

If this is such a small deal, then using an external dependency is a terrible solution. That's like the whole left-pad situation, a dependency to solve an extremely small problem, but something that affects many, many code bases. That's exactly the use case that the standard library should cover, exactly so that you don't need to use an external dependency for such a trivial thing!

And yea you could say "duh just write the extension trait in your utils module" but this is just not acknowledging the problem at all and just sidestepping it. That's not helping anyone.

[-] BB_C@programming.dev 1 points 2 days ago

Well I would say this is not at all specific to the codebase

I was talking about what a codebase would want a non-Result-returning lock() to look like (the panic message, or forcing abort, extra logging, signal handling...etc).

since poisoning is so rarely relevant.

Poisoning (as a negative) is only relevant if we are pretending it matters for performance. And you already conceded that this is not a part of the conversation as far as you're concerned.

The "rarely relevant" (as in playing any operative role at all) is also pure conjecture, or if we want to be nicer, it's totally contextual and use-case dependant.

then using an external dependency is a terrible solution.

lock_api provides a generic interface so you can e.g. seamlessly swipe out primitives from parking_lot with primitives from spin, you know, the whole point behind generic programming!

This is in no way comparable with leftpad. And I wasn't actually pointing to it as a solution (to the largely non-existing problem). I just wanted to point out that extension traits for synchronisation primitives already exist with wide usage in the ecosystem, since you seemed to not be aware.

If you have an aversion to extension traits. Here is a trivial unit struct wrapper solution. You don't even need to change the Mutex type name or the lock() method name in your code.

use std::ops::{Deref, DerefMut};
use std::sync::Mutex as PMutex;

#[repr(transparent)]
struct Mutex<T>(PMutex<T>);

impl<T> Deref for Mutex<T> {
    type Target = PMutex<T>;
    fn deref(&self) -> &Self::Target { &self.0 }
}

impl<T> DerefMut for Mutex<T> {
    fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 }
}

impl<T> Mutex<T> {
    fn new(v: T) -> Self {
        Self(PMutex::new(v))
    }

    fn lock<'a>(&'a self) ->  std::sync::MutexGuard<'a, T> {
        self.0.lock().expect("poisoned")
    }
}

fn main() {
    let m = Mutex::new(false);
    // oh look, it's a non-Result returning lock()
    *m.lock() = true;
    dbg!(*m.lock());
    // inner Mutex method API is still available via Deref/DerefMut
    *m.try_lock().unwrap() = false;
    dbg!(*m.lock());
}

And yea you could say “duh just write the extension trait in your utils module” but this is just not acknowledging the problem at all and just sidestepping it. That’s not helping anyone.

What is the notable relevant problem. Can you state it plainly?

[-] SorteKanin@feddit.dk 1 points 2 days ago

I already told you, convenience, developer experience. Ergonomics basically. None of this is fixed by some code snippet, whether it's an extension trait or wrapper type. That just makes things worse. This has nothing to do with performance, as I already said.

[-] BB_C@programming.dev 1 points 2 days ago

convenience, developer experience. Ergonomics basically.

Can you point the notable relevant inconvenience, bad developer experience, and poor ergonomics developers are suffering from?

Is it all caused by a lock() method returning a Result?
Anything else?

[-] SorteKanin@feddit.dk 2 points 1 day ago

Yes? I think I am done with this conversation. If you don't think this is a problem, we just disagree. Just move on, you don't have to convince everyone else who's been discussing this problem for years that it isn't a problem.

[-] BB_C@programming.dev 0 points 1 day ago

everyone else who’s been discussing this problem for years that it isn’t a problem.

I haven't seen anyone else concede the performance talking point (under different banners), but proceeding to make this out to be a big issue. This includes this thread's OP which literally starts on-topic arguments with:

How poisoning harms every single piece of code

As discussed in too much detail above, (un)locking mutexes is cheap as long as they’re not contended, and when contended, they are at least cheap instruction wise. This is where poisoning mutexes get you.

This is what makes your positioning weird.

My replies here, starting with pointing out the lack of benchmarks of real-world use-cases, come from actually bothering to read OP, IN FULL.

[-] BB_C@programming.dev -4 points 2 days ago

Notice the lack of any benchmarks for any real load from a real use-case.

this post was submitted on 18 Nov 2026
36 points (100.0% liked)

Rust

8379 readers
30 users here now

Welcome to the Rust community! This is a place to discuss about the Rust programming language.

Wormhole

!performance@programming.dev

Credits

  • The icon is a modified version of the official rust logo (changing the colors to a gradient and black background)

founded 3 years ago
MODERATORS