1 use crate::sys::locks as imp;
3 /// An OS-based mutual exclusion lock, meant for use in static variables.
5 /// This mutex has a const constructor ([`StaticMutex::new`]), does not
6 /// implement `Drop` to cleanup resources, and causes UB when used reentrantly.
8 /// This mutex does not implement poisoning.
10 /// This is a wrapper around `imp::Mutex` that does *not* call `init()` and
12 pub struct StaticMutex(imp::Mutex);
14 unsafe impl Sync for StaticMutex {}
17 /// Creates a new mutex for use.
19 pub const fn new() -> Self {
20 Self(imp::Mutex::new())
23 /// Calls raw_lock() and then returns an RAII guard to guarantee the mutex
26 /// It is undefined behaviour to call this function while locked by the
29 pub unsafe fn lock(&'static self) -> StaticMutexGuard {
31 StaticMutexGuard(&self.0)
36 pub struct StaticMutexGuard(&'static imp::Mutex);
38 impl Drop for StaticMutexGuard {
47 /// An OS-based mutual exclusion lock.
49 /// This mutex does *not* have a const constructor, cleans up its resources in
50 /// its `Drop` implementation, may safely be moved (when not borrowed), and
51 /// does not cause UB when used reentrantly.
53 /// This mutex does not implement poisoning.
55 /// This is either a wrapper around `Box<imp::Mutex>` or `imp::Mutex`,
56 /// depending on the platform. It is boxed on platforms where `imp::Mutex` may
58 pub struct MovableMutex(imp::MovableMutex);
60 unsafe impl Sync for MovableMutex {}
63 /// Creates a new mutex.
65 pub fn new() -> Self {
66 Self(imp::MovableMutex::new())
69 pub(super) fn raw(&self) -> &imp::Mutex {
73 /// Locks the mutex blocking the current thread until it is available.
75 pub fn raw_lock(&self) {
76 unsafe { self.0.lock() }
79 /// Attempts to lock the mutex without blocking, returning whether it was
80 /// successfully acquired or not.
82 pub fn try_lock(&self) -> bool {
83 unsafe { self.0.try_lock() }
86 /// Unlocks the mutex.
88 /// Behavior is undefined if the current thread does not actually hold the
91 pub unsafe fn raw_unlock(&self) {