about summary refs log tree commit diff
path: root/library/std/src/sys/sync/rwlock/xous.rs
blob: ab45b33e1f69be69d552913de0bc2c1981a2194b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
use crate::sync::atomic::{AtomicIsize, Ordering::Acquire};
use crate::thread::yield_now;

pub struct RwLock {
    /// The "mode" value indicates how many threads are waiting on this
    /// Mutex. Possible values are:
    ///    -1: The lock is locked for writing
    ///     0: The lock is unlocked
    ///   >=1: The lock is locked for reading
    ///
    /// This currently spins waiting for the lock to be freed. An
    /// optimization would be to involve the ticktimer server to
    /// coordinate unlocks.
    mode: AtomicIsize,
}

const RWLOCK_WRITING: isize = -1;
const RWLOCK_FREE: isize = 0;

unsafe impl Send for RwLock {}
unsafe impl Sync for RwLock {}

impl RwLock {
    #[inline]
    #[rustc_const_stable(feature = "const_locks", since = "1.63.0")]
    pub const fn new() -> RwLock {
        RwLock { mode: AtomicIsize::new(RWLOCK_FREE) }
    }

    #[inline]
    pub unsafe fn read(&self) {
        while !unsafe { self.try_read() } {
            yield_now();
        }
    }

    #[inline]
    pub unsafe fn try_read(&self) -> bool {
        self.mode
            .fetch_update(
                Acquire,
                Acquire,
                |v| if v == RWLOCK_WRITING { None } else { Some(v + 1) },
            )
            .is_ok()
    }

    #[inline]
    pub unsafe fn write(&self) {
        while !unsafe { self.try_write() } {
            yield_now();
        }
    }

    #[inline]
    pub unsafe fn try_write(&self) -> bool {
        self.mode.compare_exchange(RWLOCK_FREE, RWLOCK_WRITING, Acquire, Acquire).is_ok()
    }

    #[inline]
    pub unsafe fn read_unlock(&self) {
        let previous = self.mode.fetch_sub(1, Acquire);
        assert!(previous != RWLOCK_FREE);
        assert!(previous != RWLOCK_WRITING);
    }

    #[inline]
    pub unsafe fn write_unlock(&self) {
        assert_eq!(
            self.mode.compare_exchange(RWLOCK_WRITING, RWLOCK_FREE, Acquire, Acquire),
            Ok(RWLOCK_WRITING)
        );
    }
}