#read-write #rwlock #thread #once #condvar #mutex #deadlock

read-write-api

Provides an interface to unify single-threaded code and RwLocks-based code

3 releases

0.17.2 Sep 7, 2023
0.17.1 Sep 7, 2023
0.17.0 Jun 27, 2023
0.16.4 Jun 25, 2023
0.12.1 Jun 23, 2023

#967 in Concurrency

Download history 3/week @ 2024-07-22 19/week @ 2024-09-23 2/week @ 2024-09-30

79 downloads per month

MIT license

27KB
494 lines

Provides an interface to unify single-threaded code and RwLocks-based code.

A nice side effect of this trait is manifested in the activation of the borrow-checker to check the absence of deadlocks introduced in the current scope. This is because Self::write can now only be called on a mutable, but not constant, reference.

Example

use parking_lot::RwLock;
use read_write_api::{
    DowngradableWriteGuard,
    RwApi,
    RwApiWrapper,
    RwApiWrapperOwned,
    UpgradableReadGuard,
};

fn do_something(mut x: impl RwApi<Target=u64>) -> u64 {
    let guard = x.upgradable_read();
    if *guard == 1 {
        let mut guard = guard.upgrade_to_downgradable();
        *guard = 2;
        *guard.downgrade()
    } else {
        *guard
    }
}

assert_eq!(do_something(RwApiWrapperOwned(1)), 2);
assert_eq!(do_something(RwApiWrapperOwned(3)), 3);
assert_eq!(do_something(&mut RwApiWrapperOwned(1)), 2);
assert_eq!(do_something(&mut RwApiWrapperOwned(3)), 3);

assert_eq!(do_something(RwLock::new(1)), 2);
assert_eq!(do_something(RwLock::new(3)), 3);
assert_eq!(do_something(&RwLock::new(1)), 2);
assert_eq!(do_something(&RwLock::new(3)), 3);
assert_eq!(do_something(&mut RwLock::new(1)), 2);
assert_eq!(do_something(&mut RwLock::new(3)), 3);

fn do_something_ref<'a>(mut x: impl RwApi<Target=&'a mut u64>) -> u64 {
    if **x.read() == 1 {
        **x.write() = 2;
        **x.read()
    } else {
        **x.read()
    }
}

assert_eq!(do_something_ref(RwApiWrapper(&mut 1)), 2);
assert_eq!(do_something_ref(RwApiWrapper(&mut 3)), 3);
assert_eq!(do_something_ref(&mut RwApiWrapper(&mut 1)), 2);
assert_eq!(do_something_ref(&mut RwApiWrapper(&mut 3)), 3);

assert_eq!(do_something_ref(RwLock::new(&mut 1)), 2);
assert_eq!(do_something_ref(RwLock::new(&mut 3)), 3);
assert_eq!(do_something_ref(&RwLock::new(&mut 1)), 2);
assert_eq!(do_something_ref(&RwLock::new(&mut 3)), 3);
assert_eq!(do_something_ref(&mut RwLock::new(&mut 1)), 2);
assert_eq!(do_something_ref(&mut RwLock::new(&mut 3)), 3);

Dependencies

~0.4–5MB
~11K SLoC