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 pub type MovableMutex = Mutex;
16 /// Create a mutex object. This function never panics.
17 fn new_mtx() -> Result<abi::ID, ItronError> {
18 ItronError::err_if_negative(unsafe {
19 abi::acre_mtx(&abi::T_CMTX {
20 // Priority inheritance mutex
21 mtxatr: abi::TA_INHERIT,
30 pub const fn new() -> Mutex {
31 Mutex { mtx: SpinIdOnceCell::new() }
34 /// Get the inner mutex's ID, which is lazily created.
35 fn raw(&self) -> abi::ID {
36 match self.mtx.get_or_try_init(|| new_mtx().map(|id| (id, ()))) {
38 Err(e) => fail(e, &"acre_mtx"),
42 pub unsafe fn lock(&self) {
44 expect_success(unsafe { abi::loc_mtx(mtx) }, &"loc_mtx");
47 pub unsafe fn unlock(&self) {
48 let mtx = unsafe { self.mtx.get_unchecked().0 };
49 expect_success_aborting(unsafe { abi::unl_mtx(mtx) }, &"unl_mtx");
52 pub unsafe fn try_lock(&self) -> bool {
54 match unsafe { abi::ploc_mtx(mtx) } {
55 abi::E_TMOUT => false,
57 expect_success(er, &"ploc_mtx");
66 if let Some(mtx) = self.mtx.get().map(|x| x.0) {
67 expect_success_aborting(unsafe { abi::del_mtx(mtx) }, &"del_mtx");
72 pub(super) struct MutexGuard<'a>(&'a Mutex);
74 impl<'a> MutexGuard<'a> {
76 pub(super) fn lock(x: &'a Mutex) -> Self {
82 impl Drop for MutexGuard<'_> {
85 unsafe { self.0.unlock() };