]> git.lizzy.rs Git - rust.git/blob - library/std/src/sys_common/mutex.rs
Rollup merge of #103111 - cjgillot:shadow-label, r=estebank
[rust.git] / library / std / src / sys_common / mutex.rs
1 use crate::sys::locks as imp;
2
3 /// An OS-based mutual exclusion lock.
4 ///
5 /// This mutex cleans up its resources in its `Drop` implementation, may safely
6 /// be moved (when not borrowed), and does not cause UB when used reentrantly.
7 ///
8 /// This mutex does not implement poisoning.
9 ///
10 /// This is either a wrapper around `LazyBox<imp::Mutex>` or `imp::Mutex`,
11 /// depending on the platform. It is boxed on platforms where `imp::Mutex` may
12 /// not be moved.
13 pub struct MovableMutex(imp::MovableMutex);
14
15 unsafe impl Sync for MovableMutex {}
16
17 impl MovableMutex {
18     /// Creates a new mutex.
19     #[inline]
20     #[rustc_const_stable(feature = "const_locks", since = "1.63.0")]
21     pub const fn new() -> Self {
22         Self(imp::MovableMutex::new())
23     }
24
25     pub(super) fn raw(&self) -> &imp::Mutex {
26         &self.0
27     }
28
29     /// Locks the mutex blocking the current thread until it is available.
30     #[inline]
31     pub fn raw_lock(&self) {
32         unsafe { self.0.lock() }
33     }
34
35     /// Attempts to lock the mutex without blocking, returning whether it was
36     /// successfully acquired or not.
37     #[inline]
38     pub fn try_lock(&self) -> bool {
39         unsafe { self.0.try_lock() }
40     }
41
42     /// Unlocks the mutex.
43     ///
44     /// Behavior is undefined if the current thread does not actually hold the
45     /// mutex.
46     #[inline]
47     pub unsafe fn raw_unlock(&self) {
48         self.0.unlock()
49     }
50 }