std/sys/sync/rwlock/
no_threads.rs

1use crate::cell::Cell;
2
3pub struct RwLock {
4    // This platform has no threads, so we can use a Cell here.
5    mode: Cell<isize>,
6}
7
8unsafe impl Send for RwLock {}
9unsafe impl Sync for RwLock {} // no threads on this platform
10
11impl RwLock {
12    #[inline]
13    pub const fn new() -> RwLock {
14        RwLock { mode: Cell::new(0) }
15    }
16
17    #[inline]
18    pub fn read(&self) {
19        let m = self.mode.get();
20        if m >= 0 {
21            self.mode.set(m + 1);
22        } else {
23            rtabort!("rwlock locked for writing");
24        }
25    }
26
27    #[inline]
28    pub fn try_read(&self) -> bool {
29        let m = self.mode.get();
30        if m >= 0 {
31            self.mode.set(m + 1);
32            true
33        } else {
34            false
35        }
36    }
37
38    #[inline]
39    pub fn write(&self) {
40        if self.mode.replace(-1) != 0 {
41            rtabort!("rwlock locked for reading")
42        }
43    }
44
45    #[inline]
46    pub fn try_write(&self) -> bool {
47        if self.mode.get() == 0 {
48            self.mode.set(-1);
49            true
50        } else {
51            false
52        }
53    }
54
55    #[inline]
56    pub unsafe fn read_unlock(&self) {
57        self.mode.set(self.mode.get() - 1);
58    }
59
60    #[inline]
61    pub unsafe fn write_unlock(&self) {
62        assert_eq!(self.mode.replace(0), -1);
63    }
64
65    #[inline]
66    pub unsafe fn downgrade(&self) {
67        assert_eq!(self.mode.replace(1), -1);
68    }
69}