I noticed sometimes Rust panics to prevent a deadlock. For instance, this code panics:
let rw_lock = RwLock::new(42);
{
let data0 = rw_lock.write().unwrap();
let data1 = rw_lock.read().unwrap();
let data2 = rw_lock.read().unwrap();
}
However, this does not (it causes a deadlock instead):
let rw_lock = RwLock::new(42);
{
let data1 = rw_lock.read().unwrap();
let data2 = rw_lock.read().unwrap();
let data3 = rw_lock.write().unwrap();
}
When does Rust panic instead of doing a deadlock? And why?
According to the implementation:
// According to the pthread_rwlock_rdlock spec, this function **may**
// fail with EDEADLK if a deadlock is detected. On the other hand
// pthread mutexes will *never* return EDEADLK if they are initialized
// as the "fast" kind (which ours always are). As a result, a deadlock
// situation may actually return from the call to pthread_rwlock_rdlock
// instead of blocking forever (as mutexes and Windows rwlocks do). Note
// that not all unix implementations, however, will return EDEADLK for
// their rwlocks.
//
// We roughly maintain the deadlocking behavior by panicking to ensure
// that this lock acquisition does not succeed.
Note that this comment only applies to the UNIX variants of the RwLock
implementation, and the Windows implementation is allowed to differ. In fact, it has no panic!
statements.
Guessing a bit, I can assume that this is simply a best-effort attempt at reporting a common error case, and cannot be relied on for anything official.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With