RwLock 什么时候会恐慌而不是死锁?

When does RwLock panic instead of doing a deadlock?

我注意到有时 Rust 会恐慌以防止死锁。 例如,这段代码恐慌:

let rw_lock = RwLock::new(42);
{
    let data0 = rw_lock.write().unwrap();
    let data1 = rw_lock.read().unwrap();
    let data2 = rw_lock.read().unwrap();
}

但是,这不会(反而会导致死锁):

let rw_lock = RwLock::new(42);
{
    let data1 = rw_lock.read().unwrap();
    let data2 = rw_lock.read().unwrap();
    let data3 = rw_lock.write().unwrap();
}

Rust 什么时候会恐慌而不是死锁? 为什么?

根据 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.

请注意,此注释仅适用于 RwLock 实现的 UNIX 变体,Windows implementation 允许不同。事实上,它没有 panic! 语句。

稍微猜测一下,我可以假设这只是报告常见错误案例的最大努力尝试,不能依赖任何官方信息。