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.
18 pub const fn new() -> Self {
19 Self(imp::Mutex::new())
22 /// Calls raw_lock() and then returns an RAII guard to guarantee the mutex
25 /// It is undefined behaviour to call this function while locked by the
28 pub unsafe fn lock(&'static self) -> StaticMutexGuard {
30 StaticMutexGuard(&self.0)
35 pub struct StaticMutexGuard(&'static imp::Mutex);
37 impl Drop for StaticMutexGuard {
46 /// An OS-based mutual exclusion lock.
48 /// This mutex does *not* have a const constructor, cleans up its resources in
49 /// its `Drop` implementation, may safely be moved (when not borrowed), and
50 /// does not cause UB when used reentrantly.
52 /// This mutex does not implement poisoning.
54 /// This is either a wrapper around `Box<imp::Mutex>` or `imp::Mutex`,
55 /// depending on the platform. It is boxed on platforms where `imp::Mutex` may
57 pub struct MovableMutex(imp::MovableMutex);
59 unsafe impl Sync for MovableMutex {}
62 /// Creates a new mutex.
63 pub fn new() -> Self {
64 Self(imp::MovableMutex::new())
67 pub(super) fn raw(&self) -> &imp::Mutex {
71 /// Locks the mutex blocking the current thread until it is available.
73 pub fn raw_lock(&self) {
74 unsafe { self.0.lock() }
77 /// Attempts to lock the mutex without blocking, returning whether it was
78 /// successfully acquired or not.
80 pub fn try_lock(&self) -> bool {
81 unsafe { self.0.try_lock() }
84 /// Unlocks the mutex.
86 /// Behavior is undefined if the current thread does not actually hold the
89 pub unsafe fn raw_unlock(&self) {