Skip to main content

forge/os/
mutex.rs

1use core::cell::UnsafeCell;
2
3use sys::os::mutex::*;
4
5/// A mutual exclusion primitive for protecting shared data.
6pub struct Mutex {
7    inner: UnsafeCell<MutexType>,
8}
9
10impl Mutex {
11    /// Creates a non-recursive mutex.
12    pub fn new() -> Self {
13        Self::new_internal(false)
14    }
15
16    /// Creates a recursive mutex that can be locked multiple times by the same thread.
17    pub fn recursive() -> Self {
18        Self::new_internal(true)
19    }
20
21    /// Destroys the mutex. Called automatically on drop.
22    pub fn finalize(&self) {
23        unsafe { nnosFinalizeMutex(self.ptr()) };
24    }
25
26    /// Acquires the mutex, blocking until it is available.
27    pub fn lock(&self) {
28        unsafe { nnosLockMutex(self.ptr()) };
29    }
30
31    /// Attempts to acquire the mutex without blocking. Returns `true` on success.
32    pub fn try_lock(&self) -> bool {
33        unsafe { nnosTryLockMutex(self.ptr()) }
34    }
35
36    /// Releases the mutex.
37    pub fn unlock(&self) {
38        unsafe { nnosUnlockMutex(self.ptr()) };
39    }
40
41    pub(crate) fn ptr(&self) -> *mut MutexType {
42        self.inner.get()
43    }
44
45    fn new_internal(recursive: bool) -> Self {
46        let mut inner = MutexType::default();
47        unsafe { nnosInitializeMutex(&mut inner as *mut MutexType, recursive, 0) };
48        Self {
49            inner: UnsafeCell::new(inner),
50        }
51    }
52}
53
54impl Drop for Mutex {
55    fn drop(&mut self) {
56        todo!()
57    }
58}