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

ant*_*oyo 5 deadlock rust

我注意到有时 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();
}
Run Code Online (Sandbox Code Playgroud)

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

let rw_lock = RwLock::new(42);
{
    let data1 = rw_lock.read().unwrap();
    let data2 = rw_lock.read().unwrap();
    let data3 = rw_lock.write().unwrap();
}
Run Code Online (Sandbox Code Playgroud)

Rust 什么时候会恐慌而不是陷入僵局?为什么?

She*_*ter 5

根据实施

// 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.
Run Code Online (Sandbox Code Playgroud)

请注意,此注释仅适用于实现的 UNIX 变体RwLock,并且Windows 实现允许不同。事实上,它没有任何panic!声明。

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