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