1

futures::lock::Mutex is not implementing RefUnwindSafe trait (see https://docs.rs/futures/0.3.17/futures/lock/struct.Mutex.html#impl-RefUnwindSafe )

Why is not safe to pass a futures::lock::Mutex inside std::panic::catch_unwind?

Reproducible code:

use std::panic::catch_unwind;
use futures::lock::Mutex;

fn main() {
    let m = Mutex::new(String::new());
    
    catch_unwind(|| {
      m.lock()
    });
}

Could futures::lock::Mutex implement the RefUnwindSafe trait ?

user2722968
  • 13,636
  • 2
  • 46
  • 67
allevo
  • 844
  • 1
  • 9
  • 20

1 Answers1

1

The documentation for the UnwindSafe trait hints at a reason for this:

Who implements UnwindSafe?

Types such as &mut T and &RefCell are examples which are not unwind safe. The general idea is that any mutable state which can be shared across catch_unwind is not unwind safe by default. This is because it is very easy to witness a broken invariant outside of catch_unwind as the data is simply accessed as usual.

Types like &Mutex, however, are unwind safe because they implement poisoning by default. They still allow witnessing a broken invariant, but they already provide their own “speed bumps” to do so.

futures::lock::Mutex provides mutability like &mut T and RefCell<T>, but does not implement the poisoning feature of std::sync::Mutex<T>, so it does not implement UnwindSafe.

Though as the documentation points out, the UnwindSafe is less about memory safety and more about upholding logical invariants - hence why neither UnwindSafe nor AssertUnwindSafe are unsafe.

Colonel Thirty Two
  • 23,953
  • 8
  • 45
  • 85