]> git.lizzy.rs Git - rust.git/blob - library/std/src/sys/unix/mutex.rs
std/sys/unix/time: make it easier for LLVM to optimize `Instant` subtraction.
[rust.git] / library / std / src / sys / unix / mutex.rs
1 use crate::cell::UnsafeCell;
2 use crate::mem::MaybeUninit;
3
4 pub struct Mutex {
5     inner: UnsafeCell<libc::pthread_mutex_t>,
6 }
7
8 #[inline]
9 pub unsafe fn raw(m: &Mutex) -> *mut libc::pthread_mutex_t {
10     m.inner.get()
11 }
12
13 unsafe impl Send for Mutex {}
14 unsafe impl Sync for Mutex {}
15
16 #[allow(dead_code)] // sys isn't exported yet
17 impl Mutex {
18     pub const fn new() -> Mutex {
19         // Might be moved to a different address, so it is better to avoid
20         // initialization of potentially opaque OS data before it landed.
21         // Be very careful using this newly constructed `Mutex`, reentrant
22         // locking is undefined behavior until `init` is called!
23         Mutex { inner: UnsafeCell::new(libc::PTHREAD_MUTEX_INITIALIZER) }
24     }
25     #[inline]
26     pub unsafe fn init(&mut self) {
27         // Issue #33770
28         //
29         // A pthread mutex initialized with PTHREAD_MUTEX_INITIALIZER will have
30         // a type of PTHREAD_MUTEX_DEFAULT, which has undefined behavior if you
31         // try to re-lock it from the same thread when you already hold a lock
32         // (https://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_mutex_init.html).
33         // This is the case even if PTHREAD_MUTEX_DEFAULT == PTHREAD_MUTEX_NORMAL
34         // (https://github.com/rust-lang/rust/issues/33770#issuecomment-220847521) -- in that
35         // case, `pthread_mutexattr_settype(PTHREAD_MUTEX_DEFAULT)` will of course be the same
36         // as setting it to `PTHREAD_MUTEX_NORMAL`, but not setting any mode will result in
37         // a Mutex where re-locking is UB.
38         //
39         // In practice, glibc takes advantage of this undefined behavior to
40         // implement hardware lock elision, which uses hardware transactional
41         // memory to avoid acquiring the lock. While a transaction is in
42         // progress, the lock appears to be unlocked. This isn't a problem for
43         // other threads since the transactional memory will abort if a conflict
44         // is detected, however no abort is generated when re-locking from the
45         // same thread.
46         //
47         // Since locking the same mutex twice will result in two aliasing &mut
48         // references, we instead create the mutex with type
49         // PTHREAD_MUTEX_NORMAL which is guaranteed to deadlock if we try to
50         // re-lock it from the same thread, thus avoiding undefined behavior.
51         let mut attr = MaybeUninit::<libc::pthread_mutexattr_t>::uninit();
52         let r = libc::pthread_mutexattr_init(attr.as_mut_ptr());
53         debug_assert_eq!(r, 0);
54         let r = libc::pthread_mutexattr_settype(attr.as_mut_ptr(), libc::PTHREAD_MUTEX_NORMAL);
55         debug_assert_eq!(r, 0);
56         let r = libc::pthread_mutex_init(self.inner.get(), attr.as_ptr());
57         debug_assert_eq!(r, 0);
58         let r = libc::pthread_mutexattr_destroy(attr.as_mut_ptr());
59         debug_assert_eq!(r, 0);
60     }
61     #[inline]
62     pub unsafe fn lock(&self) {
63         let r = libc::pthread_mutex_lock(self.inner.get());
64         debug_assert_eq!(r, 0);
65     }
66     #[inline]
67     pub unsafe fn unlock(&self) {
68         let r = libc::pthread_mutex_unlock(self.inner.get());
69         debug_assert_eq!(r, 0);
70     }
71     #[inline]
72     pub unsafe fn try_lock(&self) -> bool {
73         libc::pthread_mutex_trylock(self.inner.get()) == 0
74     }
75     #[inline]
76     #[cfg(not(target_os = "dragonfly"))]
77     pub unsafe fn destroy(&self) {
78         let r = libc::pthread_mutex_destroy(self.inner.get());
79         debug_assert_eq!(r, 0);
80     }
81     #[inline]
82     #[cfg(target_os = "dragonfly")]
83     pub unsafe fn destroy(&self) {
84         let r = libc::pthread_mutex_destroy(self.inner.get());
85         // On DragonFly pthread_mutex_destroy() returns EINVAL if called on a
86         // mutex that was just initialized with libc::PTHREAD_MUTEX_INITIALIZER.
87         // Once it is used (locked/unlocked) or pthread_mutex_init() is called,
88         // this behaviour no longer occurs.
89         debug_assert!(r == 0 || r == libc::EINVAL);
90     }
91 }
92
93 pub struct ReentrantMutex {
94     inner: UnsafeCell<libc::pthread_mutex_t>,
95 }
96
97 unsafe impl Send for ReentrantMutex {}
98 unsafe impl Sync for ReentrantMutex {}
99
100 impl ReentrantMutex {
101     pub const unsafe fn uninitialized() -> ReentrantMutex {
102         ReentrantMutex { inner: UnsafeCell::new(libc::PTHREAD_MUTEX_INITIALIZER) }
103     }
104
105     pub unsafe fn init(&self) {
106         let mut attr = MaybeUninit::<libc::pthread_mutexattr_t>::uninit();
107         let result = libc::pthread_mutexattr_init(attr.as_mut_ptr());
108         debug_assert_eq!(result, 0);
109         let result =
110             libc::pthread_mutexattr_settype(attr.as_mut_ptr(), libc::PTHREAD_MUTEX_RECURSIVE);
111         debug_assert_eq!(result, 0);
112         let result = libc::pthread_mutex_init(self.inner.get(), attr.as_ptr());
113         debug_assert_eq!(result, 0);
114         let result = libc::pthread_mutexattr_destroy(attr.as_mut_ptr());
115         debug_assert_eq!(result, 0);
116     }
117
118     pub unsafe fn lock(&self) {
119         let result = libc::pthread_mutex_lock(self.inner.get());
120         debug_assert_eq!(result, 0);
121     }
122
123     #[inline]
124     pub unsafe fn try_lock(&self) -> bool {
125         libc::pthread_mutex_trylock(self.inner.get()) == 0
126     }
127
128     pub unsafe fn unlock(&self) {
129         let result = libc::pthread_mutex_unlock(self.inner.get());
130         debug_assert_eq!(result, 0);
131     }
132
133     pub unsafe fn destroy(&self) {
134         let result = libc::pthread_mutex_destroy(self.inner.get());
135         debug_assert_eq!(result, 0);
136     }
137 }