gpt4 book ai didi

rust - RwLock 什么时候会 panic 而不是死锁?

转载 作者:行者123 更新时间:2023-11-29 07:54:38 24 4
gpt4 key购买 nike

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

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 什么时候会 panic 而不是死锁?为什么?

最佳答案

根据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! 语句。

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

关于rust - RwLock 什么时候会 panic 而不是死锁?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33809005/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com