]> git.proxmox.com Git - rustc.git/blob - src/libstd/sys/common/mutex.rs
New upstream version 1.13.0+dfsg1
[rustc.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 sys::mutex as imp;
12
13 /// An OS-based mutual exclusion lock.
14 ///
15 /// This is the thinnest cross-platform wrapper around OS mutexes. All usage of
16 /// this mutex is unsafe and it is recommended to instead use the safe wrapper
17 /// at the top level of the crate instead of this type.
18 pub struct Mutex(imp::Mutex);
19
20 unsafe impl Sync for Mutex {}
21
22 impl Mutex {
23 /// Creates a new mutex for use.
24 ///
25 /// Behavior is undefined if the mutex is moved after it is
26 /// first used with any of the functions below.
27 pub const fn new() -> Mutex { Mutex(imp::Mutex::new()) }
28
29 /// Prepare the mutex for use.
30 ///
31 /// This should be called once the mutex is at a stable memory address.
32 #[inline]
33 pub unsafe fn init(&mut self) { self.0.init() }
34
35 /// Locks the mutex blocking the current thread until it is available.
36 ///
37 /// Behavior is undefined if the mutex has been moved between this and any
38 /// previous function call.
39 #[inline]
40 pub unsafe fn lock(&self) { self.0.lock() }
41
42 /// Attempts to lock the mutex without blocking, returning whether it was
43 /// successfully acquired or not.
44 ///
45 /// Behavior is undefined if the mutex has been moved between this and any
46 /// previous function call.
47 #[inline]
48 pub unsafe fn try_lock(&self) -> bool { self.0.try_lock() }
49
50 /// Unlocks the mutex.
51 ///
52 /// Behavior is undefined if the current thread does not actually hold the
53 /// mutex.
54 #[inline]
55 pub unsafe fn unlock(&self) { self.0.unlock() }
56
57 /// Deallocates all resources associated with this mutex.
58 ///
59 /// Behavior is undefined if there are current or will be future users of
60 /// this mutex.
61 #[inline]
62 pub unsafe fn destroy(&self) { self.0.destroy() }
63 }
64
65 // not meant to be exported to the outside world, just the containing module
66 pub fn raw(mutex: &Mutex) -> &imp::Mutex { &mutex.0 }