1 //! Mutex implementation backed by μITRON mutexes. Assumes `acre_mtx` and
2 //! `TA_INHERIT` are available.
5 error::{expect_success, expect_success_aborting, fail, ItronError},
10 /// The ID of the underlying mutex object
11 mtx: SpinIdOnceCell<()>,
14 /// Create a mutex object. This function never panics.
15 fn new_mtx() -> Result<abi::ID, ItronError> {
16 ItronError::err_if_negative(unsafe {
17 abi::acre_mtx(&abi::T_CMTX {
18 // Priority inheritance mutex
19 mtxatr: abi::TA_INHERIT,
28 pub const fn new() -> Mutex {
29 Mutex { mtx: SpinIdOnceCell::new() }
32 /// Get the inner mutex's ID, which is lazily created.
33 fn raw(&self) -> abi::ID {
34 match self.mtx.get_or_try_init(|| new_mtx().map(|id| (id, ()))) {
36 Err(e) => fail(e, &"acre_mtx"),
42 expect_success(unsafe { abi::loc_mtx(mtx) }, &"loc_mtx");
45 pub unsafe fn unlock(&self) {
46 let mtx = unsafe { self.mtx.get_unchecked().0 };
47 expect_success_aborting(unsafe { abi::unl_mtx(mtx) }, &"unl_mtx");
50 pub fn try_lock(&self) -> bool {
52 match unsafe { abi::ploc_mtx(mtx) } {
53 abi::E_TMOUT => false,
55 expect_success(er, &"ploc_mtx");
64 if let Some(mtx) = self.mtx.get().map(|x| x.0) {
65 expect_success_aborting(unsafe { abi::del_mtx(mtx) }, &"del_mtx");
70 pub(super) struct MutexGuard<'a>(&'a Mutex);
72 impl<'a> MutexGuard<'a> {
74 pub(super) fn lock(x: &'a Mutex) -> Self {
80 impl Drop for MutexGuard<'_> {
83 unsafe { self.0.unlock() };