我注意到有时会出现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什么时候发生恐慌而不是陷入僵局? 为什么?
答案 0 :(得分:4)
// 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!
个陈述。
猜测一下,我可以假设这只是报告常见错误案例的最佳尝试,并且不能依赖任何官方错误。