When does RwLock panic rather than make a standstill?

Sometimes I noticed a panic in Rust to prevent a dead end. For example, this code is panicky:

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 happen (instead, it causes a dead end):

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 a rusty panic arise, not a dead end? And why?

+4
source share
1 answer

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.

Please note that this comment only applies to UNIX implementation options RwLock, and the Windows implementation may vary. In fact, it has no operators panic!.

Having guessed a little, I can assume that this is just an attempt to try to report a general case of a mistake, and you cannot rely on it for anything official.

+4
source

Source: https://habr.com/ru/post/1616588/


All Articles