]> git.lizzy.rs Git - rust.git/blob - library/std/src/sync/mutex.rs
std: move "mod tests/benches" to separate files
[rust.git] / library / std / src / sync / mutex.rs
1 #[cfg(all(test, not(target_os = "emscripten")))]
2 mod tests;
3
4 use crate::cell::UnsafeCell;
5 use crate::fmt;
6 use crate::mem;
7 use crate::ops::{Deref, DerefMut};
8 use crate::ptr;
9 use crate::sys_common::mutex as sys;
10 use crate::sys_common::poison::{self, LockResult, TryLockError, TryLockResult};
11
12 /// A mutual exclusion primitive useful for protecting shared data
13 ///
14 /// This mutex will block threads waiting for the lock to become available. The
15 /// mutex can also be statically initialized or created via a [`new`]
16 /// constructor. Each mutex has a type parameter which represents the data that
17 /// it is protecting. The data can only be accessed through the RAII guards
18 /// returned from [`lock`] and [`try_lock`], which guarantees that the data is only
19 /// ever accessed when the mutex is locked.
20 ///
21 /// # Poisoning
22 ///
23 /// The mutexes in this module implement a strategy called "poisoning" where a
24 /// mutex is considered poisoned whenever a thread panics while holding the
25 /// mutex. Once a mutex is poisoned, all other threads are unable to access the
26 /// data by default as it is likely tainted (some invariant is not being
27 /// upheld).
28 ///
29 /// For a mutex, this means that the [`lock`] and [`try_lock`] methods return a
30 /// [`Result`] which indicates whether a mutex has been poisoned or not. Most
31 /// usage of a mutex will simply [`unwrap()`] these results, propagating panics
32 /// among threads to ensure that a possibly invalid invariant is not witnessed.
33 ///
34 /// A poisoned mutex, however, does not prevent all access to the underlying
35 /// data. The [`PoisonError`] type has an [`into_inner`] method which will return
36 /// the guard that would have otherwise been returned on a successful lock. This
37 /// allows access to the data, despite the lock being poisoned.
38 ///
39 /// [`new`]: Self::new
40 /// [`lock`]: Self::lock
41 /// [`try_lock`]: Self::try_lock
42 /// [`unwrap()`]: Result::unwrap
43 /// [`PoisonError`]: super::PoisonError
44 /// [`into_inner`]: super::PoisonError::into_inner
45 ///
46 /// # Examples
47 ///
48 /// ```
49 /// use std::sync::{Arc, Mutex};
50 /// use std::thread;
51 /// use std::sync::mpsc::channel;
52 ///
53 /// const N: usize = 10;
54 ///
55 /// // Spawn a few threads to increment a shared variable (non-atomically), and
56 /// // let the main thread know once all increments are done.
57 /// //
58 /// // Here we're using an Arc to share memory among threads, and the data inside
59 /// // the Arc is protected with a mutex.
60 /// let data = Arc::new(Mutex::new(0));
61 ///
62 /// let (tx, rx) = channel();
63 /// for _ in 0..N {
64 ///     let (data, tx) = (Arc::clone(&data), tx.clone());
65 ///     thread::spawn(move || {
66 ///         // The shared state can only be accessed once the lock is held.
67 ///         // Our non-atomic increment is safe because we're the only thread
68 ///         // which can access the shared state when the lock is held.
69 ///         //
70 ///         // We unwrap() the return value to assert that we are not expecting
71 ///         // threads to ever fail while holding the lock.
72 ///         let mut data = data.lock().unwrap();
73 ///         *data += 1;
74 ///         if *data == N {
75 ///             tx.send(()).unwrap();
76 ///         }
77 ///         // the lock is unlocked here when `data` goes out of scope.
78 ///     });
79 /// }
80 ///
81 /// rx.recv().unwrap();
82 /// ```
83 ///
84 /// To recover from a poisoned mutex:
85 ///
86 /// ```
87 /// use std::sync::{Arc, Mutex};
88 /// use std::thread;
89 ///
90 /// let lock = Arc::new(Mutex::new(0_u32));
91 /// let lock2 = lock.clone();
92 ///
93 /// let _ = thread::spawn(move || -> () {
94 ///     // This thread will acquire the mutex first, unwrapping the result of
95 ///     // `lock` because the lock has not been poisoned.
96 ///     let _guard = lock2.lock().unwrap();
97 ///
98 ///     // This panic while holding the lock (`_guard` is in scope) will poison
99 ///     // the mutex.
100 ///     panic!();
101 /// }).join();
102 ///
103 /// // The lock is poisoned by this point, but the returned result can be
104 /// // pattern matched on to return the underlying guard on both branches.
105 /// let mut guard = match lock.lock() {
106 ///     Ok(guard) => guard,
107 ///     Err(poisoned) => poisoned.into_inner(),
108 /// };
109 ///
110 /// *guard += 1;
111 /// ```
112 ///
113 /// It is sometimes necessary to manually drop the mutex guard to unlock it
114 /// sooner than the end of the enclosing scope.
115 ///
116 /// ```
117 /// use std::sync::{Arc, Mutex};
118 /// use std::thread;
119 ///
120 /// const N: usize = 3;
121 ///
122 /// let data_mutex = Arc::new(Mutex::new(vec![1, 2, 3, 4]));
123 /// let res_mutex = Arc::new(Mutex::new(0));
124 ///
125 /// let mut threads = Vec::with_capacity(N);
126 /// (0..N).for_each(|_| {
127 ///     let data_mutex_clone = Arc::clone(&data_mutex);
128 ///     let res_mutex_clone = Arc::clone(&res_mutex);
129 ///
130 ///     threads.push(thread::spawn(move || {
131 ///         let mut data = data_mutex_clone.lock().unwrap();
132 ///         // This is the result of some important and long-ish work.
133 ///         let result = data.iter().fold(0, |acc, x| acc + x * 2);
134 ///         data.push(result);
135 ///         drop(data);
136 ///         *res_mutex_clone.lock().unwrap() += result;
137 ///     }));
138 /// });
139 ///
140 /// let mut data = data_mutex.lock().unwrap();
141 /// // This is the result of some important and long-ish work.
142 /// let result = data.iter().fold(0, |acc, x| acc + x * 2);
143 /// data.push(result);
144 /// // We drop the `data` explicitly because it's not necessary anymore and the
145 /// // thread still has work to do. This allow other threads to start working on
146 /// // the data immediately, without waiting for the rest of the unrelated work
147 /// // to be done here.
148 /// //
149 /// // It's even more important here than in the threads because we `.join` the
150 /// // threads after that. If we had not dropped the mutex guard, a thread could
151 /// // be waiting forever for it, causing a deadlock.
152 /// drop(data);
153 /// // Here the mutex guard is not assigned to a variable and so, even if the
154 /// // scope does not end after this line, the mutex is still released: there is
155 /// // no deadlock.
156 /// *res_mutex.lock().unwrap() += result;
157 ///
158 /// threads.into_iter().for_each(|thread| {
159 ///     thread
160 ///         .join()
161 ///         .expect("The thread creating or execution failed !")
162 /// });
163 ///
164 /// assert_eq!(*res_mutex.lock().unwrap(), 800);
165 /// ```
166 #[stable(feature = "rust1", since = "1.0.0")]
167 #[cfg_attr(not(test), rustc_diagnostic_item = "mutex_type")]
168 pub struct Mutex<T: ?Sized> {
169     // Note that this mutex is in a *box*, not inlined into the struct itself.
170     // Once a native mutex has been used once, its address can never change (it
171     // can't be moved). This mutex type can be safely moved at any time, so to
172     // ensure that the native mutex is used correctly we box the inner mutex to
173     // give it a constant address.
174     inner: Box<sys::Mutex>,
175     poison: poison::Flag,
176     data: UnsafeCell<T>,
177 }
178
179 // these are the only places where `T: Send` matters; all other
180 // functionality works fine on a single thread.
181 #[stable(feature = "rust1", since = "1.0.0")]
182 unsafe impl<T: ?Sized + Send> Send for Mutex<T> {}
183 #[stable(feature = "rust1", since = "1.0.0")]
184 unsafe impl<T: ?Sized + Send> Sync for Mutex<T> {}
185
186 /// An RAII implementation of a "scoped lock" of a mutex. When this structure is
187 /// dropped (falls out of scope), the lock will be unlocked.
188 ///
189 /// The data protected by the mutex can be accessed through this guard via its
190 /// [`Deref`] and [`DerefMut`] implementations.
191 ///
192 /// This structure is created by the [`lock`] and [`try_lock`] methods on
193 /// [`Mutex`].
194 ///
195 /// [`lock`]: Mutex::lock
196 /// [`try_lock`]: Mutex::try_lock
197 #[must_use = "if unused the Mutex will immediately unlock"]
198 #[stable(feature = "rust1", since = "1.0.0")]
199 pub struct MutexGuard<'a, T: ?Sized + 'a> {
200     lock: &'a Mutex<T>,
201     poison: poison::Guard,
202 }
203
204 #[stable(feature = "rust1", since = "1.0.0")]
205 impl<T: ?Sized> !Send for MutexGuard<'_, T> {}
206 #[stable(feature = "mutexguard", since = "1.19.0")]
207 unsafe impl<T: ?Sized + Sync> Sync for MutexGuard<'_, T> {}
208
209 impl<T> Mutex<T> {
210     /// Creates a new mutex in an unlocked state ready for use.
211     ///
212     /// # Examples
213     ///
214     /// ```
215     /// use std::sync::Mutex;
216     ///
217     /// let mutex = Mutex::new(0);
218     /// ```
219     #[stable(feature = "rust1", since = "1.0.0")]
220     pub fn new(t: T) -> Mutex<T> {
221         let mut m = Mutex {
222             inner: box sys::Mutex::new(),
223             poison: poison::Flag::new(),
224             data: UnsafeCell::new(t),
225         };
226         unsafe {
227             m.inner.init();
228         }
229         m
230     }
231 }
232
233 impl<T: ?Sized> Mutex<T> {
234     /// Acquires a mutex, blocking the current thread until it is able to do so.
235     ///
236     /// This function will block the local thread until it is available to acquire
237     /// the mutex. Upon returning, the thread is the only thread with the lock
238     /// held. An RAII guard is returned to allow scoped unlock of the lock. When
239     /// the guard goes out of scope, the mutex will be unlocked.
240     ///
241     /// The exact behavior on locking a mutex in the thread which already holds
242     /// the lock is left unspecified. However, this function will not return on
243     /// the second call (it might panic or deadlock, for example).
244     ///
245     /// # Errors
246     ///
247     /// If another user of this mutex panicked while holding the mutex, then
248     /// this call will return an error once the mutex is acquired.
249     ///
250     /// # Panics
251     ///
252     /// This function might panic when called if the lock is already held by
253     /// the current thread.
254     ///
255     /// # Examples
256     ///
257     /// ```
258     /// use std::sync::{Arc, Mutex};
259     /// use std::thread;
260     ///
261     /// let mutex = Arc::new(Mutex::new(0));
262     /// let c_mutex = mutex.clone();
263     ///
264     /// thread::spawn(move || {
265     ///     *c_mutex.lock().unwrap() = 10;
266     /// }).join().expect("thread::spawn failed");
267     /// assert_eq!(*mutex.lock().unwrap(), 10);
268     /// ```
269     #[stable(feature = "rust1", since = "1.0.0")]
270     pub fn lock(&self) -> LockResult<MutexGuard<'_, T>> {
271         unsafe {
272             self.inner.raw_lock();
273             MutexGuard::new(self)
274         }
275     }
276
277     /// Attempts to acquire this lock.
278     ///
279     /// If the lock could not be acquired at this time, then [`Err`] is returned.
280     /// Otherwise, an RAII guard is returned. The lock will be unlocked when the
281     /// guard is dropped.
282     ///
283     /// This function does not block.
284     ///
285     /// # Errors
286     ///
287     /// If another user of this mutex panicked while holding the mutex, then
288     /// this call will return failure if the mutex would otherwise be
289     /// acquired.
290     ///
291     /// # Examples
292     ///
293     /// ```
294     /// use std::sync::{Arc, Mutex};
295     /// use std::thread;
296     ///
297     /// let mutex = Arc::new(Mutex::new(0));
298     /// let c_mutex = mutex.clone();
299     ///
300     /// thread::spawn(move || {
301     ///     let mut lock = c_mutex.try_lock();
302     ///     if let Ok(ref mut mutex) = lock {
303     ///         **mutex = 10;
304     ///     } else {
305     ///         println!("try_lock failed");
306     ///     }
307     /// }).join().expect("thread::spawn failed");
308     /// assert_eq!(*mutex.lock().unwrap(), 10);
309     /// ```
310     #[stable(feature = "rust1", since = "1.0.0")]
311     pub fn try_lock(&self) -> TryLockResult<MutexGuard<'_, T>> {
312         unsafe {
313             if self.inner.try_lock() {
314                 Ok(MutexGuard::new(self)?)
315             } else {
316                 Err(TryLockError::WouldBlock)
317             }
318         }
319     }
320
321     /// Determines whether the mutex is poisoned.
322     ///
323     /// If another thread is active, the mutex can still become poisoned at any
324     /// time. You should not trust a `false` value for program correctness
325     /// without additional synchronization.
326     ///
327     /// # Examples
328     ///
329     /// ```
330     /// use std::sync::{Arc, Mutex};
331     /// use std::thread;
332     ///
333     /// let mutex = Arc::new(Mutex::new(0));
334     /// let c_mutex = mutex.clone();
335     ///
336     /// let _ = thread::spawn(move || {
337     ///     let _lock = c_mutex.lock().unwrap();
338     ///     panic!(); // the mutex gets poisoned
339     /// }).join();
340     /// assert_eq!(mutex.is_poisoned(), true);
341     /// ```
342     #[inline]
343     #[stable(feature = "sync_poison", since = "1.2.0")]
344     pub fn is_poisoned(&self) -> bool {
345         self.poison.get()
346     }
347
348     /// Consumes this mutex, returning the underlying data.
349     ///
350     /// # Errors
351     ///
352     /// If another user of this mutex panicked while holding the mutex, then
353     /// this call will return an error instead.
354     ///
355     /// # Examples
356     ///
357     /// ```
358     /// use std::sync::Mutex;
359     ///
360     /// let mutex = Mutex::new(0);
361     /// assert_eq!(mutex.into_inner().unwrap(), 0);
362     /// ```
363     #[stable(feature = "mutex_into_inner", since = "1.6.0")]
364     pub fn into_inner(self) -> LockResult<T>
365     where
366         T: Sized,
367     {
368         // We know statically that there are no outstanding references to
369         // `self` so there's no need to lock the inner mutex.
370         //
371         // To get the inner value, we'd like to call `data.into_inner()`,
372         // but because `Mutex` impl-s `Drop`, we can't move out of it, so
373         // we'll have to destructure it manually instead.
374         unsafe {
375             // Like `let Mutex { inner, poison, data } = self`.
376             let (inner, poison, data) = {
377                 let Mutex { ref inner, ref poison, ref data } = self;
378                 (ptr::read(inner), ptr::read(poison), ptr::read(data))
379             };
380             mem::forget(self);
381             inner.destroy(); // Keep in sync with the `Drop` impl.
382             drop(inner);
383
384             poison::map_result(poison.borrow(), |_| data.into_inner())
385         }
386     }
387
388     /// Returns a mutable reference to the underlying data.
389     ///
390     /// Since this call borrows the `Mutex` mutably, no actual locking needs to
391     /// take place -- the mutable borrow statically guarantees no locks exist.
392     ///
393     /// # Errors
394     ///
395     /// If another user of this mutex panicked while holding the mutex, then
396     /// this call will return an error instead.
397     ///
398     /// # Examples
399     ///
400     /// ```
401     /// use std::sync::Mutex;
402     ///
403     /// let mut mutex = Mutex::new(0);
404     /// *mutex.get_mut().unwrap() = 10;
405     /// assert_eq!(*mutex.lock().unwrap(), 10);
406     /// ```
407     #[stable(feature = "mutex_get_mut", since = "1.6.0")]
408     pub fn get_mut(&mut self) -> LockResult<&mut T> {
409         // We know statically that there are no other references to `self`, so
410         // there's no need to lock the inner mutex.
411         let data = unsafe { &mut *self.data.get() };
412         poison::map_result(self.poison.borrow(), |_| data)
413     }
414 }
415
416 #[stable(feature = "rust1", since = "1.0.0")]
417 unsafe impl<#[may_dangle] T: ?Sized> Drop for Mutex<T> {
418     fn drop(&mut self) {
419         // This is actually safe b/c we know that there is no further usage of
420         // this mutex (it's up to the user to arrange for a mutex to get
421         // dropped, that's not our job)
422         //
423         // IMPORTANT: This code must be kept in sync with `Mutex::into_inner`.
424         unsafe { self.inner.destroy() }
425     }
426 }
427
428 #[stable(feature = "mutex_from", since = "1.24.0")]
429 impl<T> From<T> for Mutex<T> {
430     /// Creates a new mutex in an unlocked state ready for use.
431     /// This is equivalent to [`Mutex::new`].
432     fn from(t: T) -> Self {
433         Mutex::new(t)
434     }
435 }
436
437 #[stable(feature = "mutex_default", since = "1.10.0")]
438 impl<T: ?Sized + Default> Default for Mutex<T> {
439     /// Creates a `Mutex<T>`, with the `Default` value for T.
440     fn default() -> Mutex<T> {
441         Mutex::new(Default::default())
442     }
443 }
444
445 #[stable(feature = "rust1", since = "1.0.0")]
446 impl<T: ?Sized + fmt::Debug> fmt::Debug for Mutex<T> {
447     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
448         match self.try_lock() {
449             Ok(guard) => f.debug_struct("Mutex").field("data", &&*guard).finish(),
450             Err(TryLockError::Poisoned(err)) => {
451                 f.debug_struct("Mutex").field("data", &&**err.get_ref()).finish()
452             }
453             Err(TryLockError::WouldBlock) => {
454                 struct LockedPlaceholder;
455                 impl fmt::Debug for LockedPlaceholder {
456                     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
457                         f.write_str("<locked>")
458                     }
459                 }
460
461                 f.debug_struct("Mutex").field("data", &LockedPlaceholder).finish()
462             }
463         }
464     }
465 }
466
467 impl<'mutex, T: ?Sized> MutexGuard<'mutex, T> {
468     unsafe fn new(lock: &'mutex Mutex<T>) -> LockResult<MutexGuard<'mutex, T>> {
469         poison::map_result(lock.poison.borrow(), |guard| MutexGuard { lock, poison: guard })
470     }
471 }
472
473 #[stable(feature = "rust1", since = "1.0.0")]
474 impl<T: ?Sized> Deref for MutexGuard<'_, T> {
475     type Target = T;
476
477     fn deref(&self) -> &T {
478         unsafe { &*self.lock.data.get() }
479     }
480 }
481
482 #[stable(feature = "rust1", since = "1.0.0")]
483 impl<T: ?Sized> DerefMut for MutexGuard<'_, T> {
484     fn deref_mut(&mut self) -> &mut T {
485         unsafe { &mut *self.lock.data.get() }
486     }
487 }
488
489 #[stable(feature = "rust1", since = "1.0.0")]
490 impl<T: ?Sized> Drop for MutexGuard<'_, T> {
491     #[inline]
492     fn drop(&mut self) {
493         unsafe {
494             self.lock.poison.done(&self.poison);
495             self.lock.inner.raw_unlock();
496         }
497     }
498 }
499
500 #[stable(feature = "std_debug", since = "1.16.0")]
501 impl<T: ?Sized + fmt::Debug> fmt::Debug for MutexGuard<'_, T> {
502     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
503         fmt::Debug::fmt(&**self, f)
504     }
505 }
506
507 #[stable(feature = "std_guard_impls", since = "1.20.0")]
508 impl<T: ?Sized + fmt::Display> fmt::Display for MutexGuard<'_, T> {
509     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
510         (**self).fmt(f)
511     }
512 }
513
514 pub fn guard_lock<'a, T: ?Sized>(guard: &MutexGuard<'a, T>) -> &'a sys::Mutex {
515     &guard.lock.inner
516 }
517
518 pub fn guard_poison<'a, T: ?Sized>(guard: &MutexGuard<'a, T>) -> &'a poison::Flag {
519     &guard.lock.poison
520 }