]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/common/mutex.rs
Merge pull request #20674 from jbcrail/fix-misspelled-comments
[rust.git] / src / libstd / sys / common / mutex.rs
1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use marker::Sync;
12 use sys::mutex as imp;
13
14 /// An OS-based mutual exclusion lock.
15 ///
16 /// This is the thinnest cross-platform wrapper around OS mutexes. All usage of
17 /// this mutex is unsafe and it is recommended to instead use the safe wrapper
18 /// at the top level of the crate instead of this type.
19 pub struct Mutex(imp::Mutex);
20
21 unsafe impl Sync for Mutex {}
22
23 /// Constant initializer for statically allocated mutexes.
24 pub const MUTEX_INIT: Mutex = Mutex(imp::MUTEX_INIT);
25
26 impl Mutex {
27     /// Creates a newly initialized mutex.
28     ///
29     /// Behavior is undefined if the mutex is moved after the first method is
30     /// called on the mutex.
31     #[inline]
32     pub unsafe fn new() -> Mutex { Mutex(imp::Mutex::new()) }
33
34     /// Lock the mutex blocking the current thread until it is available.
35     ///
36     /// Behavior is undefined if the mutex has been moved between this and any
37     /// previous function call.
38     #[inline]
39     pub unsafe fn lock(&self) { self.0.lock() }
40
41     /// Attempt to lock the mutex without blocking, returning whether it was
42     /// successfully acquired or not.
43     ///
44     /// Behavior is undefined if the mutex has been moved between this and any
45     /// previous function call.
46     #[inline]
47     pub unsafe fn try_lock(&self) -> bool { self.0.try_lock() }
48
49     /// Unlock the mutex.
50     ///
51     /// Behavior is undefined if the current thread does not actually hold the
52     /// mutex.
53     #[inline]
54     pub unsafe fn unlock(&self) { self.0.unlock() }
55
56     /// Deallocate all resources associated with this mutex.
57     ///
58     /// Behavior is undefined if there are current or will be future users of
59     /// this mutex.
60     #[inline]
61     pub unsafe fn destroy(&self) { self.0.destroy() }
62 }
63
64 // not meant to be exported to the outside world, just the containing module
65 pub fn raw(mutex: &Mutex) -> &imp::Mutex { &mutex.0 }