aboutsummaryrefslogtreecommitdiff
path: root/embassy-sync/src/blocking_mutex/raw_rwlock.rs
blob: de4bd1dc54cb534f21d10a83ab0b215e9eb448ff (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
75
76
77
78
79
80
81
82
83
84
85
86
use core::sync::atomic::{AtomicUsize, Ordering};
use core::task::Waker;
use core::cell::UnsafeCell;

pub trait RawRwLock {
    fn lock_read(&self);
    fn try_lock_read(&self) -> bool;
    fn unlock_read(&self);
    fn lock_write(&self);
    fn try_lock_write(&self) -> bool;
    fn unlock_write(&self);
}

pub struct RawRwLockImpl {
    state: AtomicUsize,
    waker: UnsafeCell<Option<Waker>>,
}

impl RawRwLockImpl {
    pub const fn new() -> Self {
        Self {
            state: AtomicUsize::new(0),
            waker: UnsafeCell::new(None),
        }
    }
}

unsafe impl Send for RawRwLockImpl {}
unsafe impl Sync for RawRwLockImpl {}

impl RawRwLock for RawRwLockImpl {
    fn lock_read(&self) {
        loop {
            let state = self.state.load(Ordering::Acquire);
            if state & 1 == 0 {
                if self.state.compare_and_swap(state, state + 2, Ordering::AcqRel) == state {
                    break;
                }
            }
        }
    }

    fn try_lock_read(&self) -> bool {
        let state = self.state.load(Ordering::Acquire);
        if state & 1 == 0 {
            if self.state.compare_and_swap(state, state + 2, Ordering::AcqRel) == state {
                return true;
            }
        }
        false
    }

    fn unlock_read(&self) {
        self.state.fetch_sub(2, Ordering::Release);
        if self.state.load(Ordering::Acquire) == 0 {
            if let Some(waker) = unsafe { &*self.waker.get() } {
                waker.wake_by_ref();
            }
        }
    }

    fn lock_write(&self) {
        loop {
            let state = self.state.load(Ordering::Acquire);
            if state == 0 {
                if self.state.compare_and_swap(0, 1, Ordering::AcqRel) == 0 {
                    break;
                }
            }
        }
    }

    fn try_lock_write(&self) -> bool {
        if self.state.compare_and_swap(0, 1, Ordering::AcqRel) == 0 {
            return true;
        }
        false
    }

    fn unlock_write(&self) {
        self.state.store(0, Ordering::Release);
        if let Some(waker) = unsafe { &*self.waker.get() } {
            waker.wake_by_ref();
        }
    }
}