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