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
use core::{convert::TryInto, time::Duration};
use crate::{
bindings,
error::{from_errno, Error, SentinelError},
};
pub struct Semaphore(bindings::sem_t);
impl Semaphore {
#[inline]
pub fn new(max_count: u32, init_count: u32) -> Self {
Self::try_new(max_count, init_count)
.unwrap_or_else(|err| panic!("failed to create semaphore: {}", err))
}
pub fn try_new(max_count: u32, init_count: u32) -> Result<Self, Error> {
Ok(Self(
unsafe { bindings::sem_create(max_count, init_count) }.check()?,
))
}
#[inline]
pub fn wait(&self, timeout: Duration) -> Result<(), Error> {
if unsafe { bindings::sem_wait(self.0, timeout.as_millis().try_into()?) } {
Ok(())
} else {
Err(from_errno())
}
}
#[inline]
pub fn post(&self) -> Result<(), Error> {
if unsafe { bindings::sem_post(self.0) } {
Ok(())
} else {
Err(from_errno())
}
}
#[inline]
pub fn count(&self) -> u32 {
unsafe { bindings::sem_get_count(self.0) }
}
}
impl Drop for Semaphore {
fn drop(&mut self) {
unsafe { bindings::sem_delete(self.0) }
}
}
unsafe impl Send for Semaphore {}
unsafe impl Sync for Semaphore {}