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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
use super::{Event, EventBus};
use crate::error::LxError;
use alloc::boxed::Box;
use alloc::sync::Arc;
use core::future::Future;
use core::ops::Deref;
use core::pin::Pin;
use core::task::{Context, Poll};
use lock::Mutex;
pub struct Semaphore {
lock: Arc<Mutex<SemaphoreInner>>,
}
struct SemaphoreInner {
count: isize,
pid: usize,
removed: bool,
eventbus: EventBus,
}
pub struct SemaphoreGuard<'a> {
sem: &'a Semaphore,
}
impl Semaphore {
pub fn new(count: isize) -> Semaphore {
Semaphore {
lock: Arc::new(Mutex::new(SemaphoreInner {
count,
removed: false,
pid: 0,
eventbus: EventBus::default(),
})),
}
}
pub fn remove(&self) {
let mut inner = self.lock.lock();
inner.removed = true;
inner.eventbus.set(Event::SEMAPHORE_REMOVED);
}
pub async fn acquire(&self) -> Result<(), LxError> {
#[must_use = "future does nothing unless polled/`await`-ed"]
struct SemaphoreFuture {
inner: Arc<Mutex<SemaphoreInner>>,
}
impl Future for SemaphoreFuture {
type Output = Result<(), LxError>;
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
let mut inner = self.inner.lock();
if inner.removed {
return Poll::Ready(Err(LxError::EIDRM));
} else if inner.count >= 1 {
inner.count -= 1;
if inner.count < 1 {
inner.eventbus.clear(Event::SEMAPHORE_CAN_ACQUIRE);
}
return Poll::Ready(Ok(()));
}
let waker = cx.waker().clone();
inner.eventbus.subscribe(Box::new({
move |_| {
waker.wake_by_ref();
true
}
}));
Poll::Pending
}
}
let future = SemaphoreFuture {
inner: self.lock.clone(),
};
future.await
}
pub fn release(&self) {
let mut inner = self.lock.lock();
inner.count += 1;
if inner.count >= 1 {
inner.eventbus.set(Event::SEMAPHORE_CAN_ACQUIRE);
}
}
pub async fn access(&self) -> Result<SemaphoreGuard<'_>, LxError> {
self.acquire().await?;
Ok(SemaphoreGuard { sem: self })
}
pub fn get(&self) -> isize {
self.lock.lock().count
}
pub fn get_ncnt(&self) -> usize {
self.lock.lock().eventbus.get_callback_len()
}
pub fn get_pid(&self) -> usize {
self.lock.lock().pid
}
pub fn set_pid(&self, pid: usize) {
self.lock.lock().pid = pid;
}
pub fn set(&self, value: isize) {
let mut inner = self.lock.lock();
inner.count = value;
if inner.count >= 1 {
inner.eventbus.set(Event::SEMAPHORE_CAN_ACQUIRE);
}
}
}
impl Drop for SemaphoreGuard<'_> {
fn drop(&mut self) {
self.sem.release();
}
}
impl Deref for SemaphoreGuard<'_> {
type Target = Semaphore;
fn deref(&self) -> &Self::Target {
self.sem
}
}