1 use crate::sys::mutex as imp;
3 /// An OS-based mutual exclusion lock.
5 /// This is the thinnest cross-platform wrapper around OS mutexes. All usage of
6 /// this mutex is unsafe and it is recommended to instead use the safe wrapper
7 /// at the top level of the crate instead of this type.
8 pub struct Mutex(imp::Mutex);
10 unsafe impl Sync for Mutex {}
13 /// Creates a new mutex for use.
15 /// Behavior is undefined if the mutex is moved after it is
16 /// first used with any of the functions below.
17 /// Also, until `init` is called, behavior is undefined if this
18 /// mutex is ever used reentrantly, i.e., `raw_lock` or `try_lock`
19 /// are called by the thread currently holding the lock.
20 pub const fn new() -> Mutex {
21 Mutex(imp::Mutex::new())
24 /// Prepare the mutex for use.
26 /// This should be called once the mutex is at a stable memory address.
27 /// If called, this must be the very first thing that happens to the mutex.
28 /// Calling it in parallel with or after any operation (including another
29 /// `init()`) is undefined behavior.
31 pub unsafe fn init(&mut self) {
35 /// Locks the mutex blocking the current thread until it is available.
37 /// Behavior is undefined if the mutex has been moved between this and any
38 /// previous function call.
40 pub unsafe fn raw_lock(&self) {
44 /// Calls raw_lock() and then returns an RAII guard to guarantee the mutex
47 pub unsafe fn lock(&self) -> MutexGuard<'_> {
52 /// Attempts to lock the mutex without blocking, returning whether it was
53 /// successfully acquired or not.
55 /// Behavior is undefined if the mutex has been moved between this and any
56 /// previous function call.
58 pub unsafe fn try_lock(&self) -> bool {
62 /// Unlocks the mutex.
64 /// Behavior is undefined if the current thread does not actually hold the
67 /// Consider switching from the pair of raw_lock() and raw_unlock() to
68 /// lock() whenever possible.
70 pub unsafe fn raw_unlock(&self) {
74 /// Deallocates all resources associated with this mutex.
76 /// Behavior is undefined if there are current or will be future users of
79 pub unsafe fn destroy(&self) {
84 // not meant to be exported to the outside world, just the containing module
85 pub fn raw(mutex: &Mutex) -> &imp::Mutex {
90 /// A simple RAII utility for the above Mutex without the poisoning semantics.
91 pub struct MutexGuard<'a>(&'a imp::Mutex);
93 impl Drop for MutexGuard<'_> {