简体   繁体   中英

When does RwLock panic instead of doing a deadlock?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM