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 pub unsafe fn init(&mut self) {
35 // Initialize `self.mtx` eagerly
36 let id = new_mtx().unwrap_or_else(|e| fail(e, &"acre_mtx"));
37 unsafe { self.mtx.set_unchecked((id, ())) };
40 /// Get the inner mutex's ID, which is lazily created.
41 fn raw(&self) -> abi::ID {
42 match self.mtx.get_or_try_init(|| new_mtx().map(|id| (id, ()))) {
44 Err(e) => fail(e, &"acre_mtx"),
48 pub unsafe fn lock(&self) {
50 expect_success(unsafe { abi::loc_mtx(mtx) }, &"loc_mtx");
53 pub unsafe fn unlock(&self) {
54 let mtx = unsafe { self.mtx.get_unchecked().0 };
55 expect_success_aborting(unsafe { abi::unl_mtx(mtx) }, &"unl_mtx");
58 pub unsafe fn try_lock(&self) -> bool {
60 match unsafe { abi::ploc_mtx(mtx) } {
61 abi::E_TMOUT => false,
63 expect_success(er, &"ploc_mtx");
72 if let Some(mtx) = self.mtx.get().map(|x| x.0) {
73 expect_success_aborting(unsafe { abi::del_mtx(mtx) }, &"del_mtx");
78 pub(super) struct MutexGuard<'a>(&'a Mutex);
80 impl<'a> MutexGuard<'a> {
82 pub(super) fn lock(x: &'a Mutex) -> Self {
88 impl Drop for MutexGuard<'_> {
91 unsafe { self.0.unlock() };