Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does RwLock panic instead of doing a deadlock?

Tags:

rust

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?

like image 682
antoyo Avatar asked Nov 19 '15 16:11

antoyo


1 Answers

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.

like image 194
Shepmaster Avatar answered Nov 15 '22 09:11

Shepmaster