]> git.proxmox.com Git - rustc.git/blob - library/std/src/sync/mutex.rs
New upstream version 1.54.0+dfsg1
[rustc.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_type")]
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 #[stable(feature = "rust1", since = "1.0.0")]
192 pub struct MutexGuard<'a, T: ?Sized + 'a> {
193 lock: &'a Mutex<T>,
194 poison: poison::Guard,
195 }
196
197 #[stable(feature = "rust1", since = "1.0.0")]
198 impl<T: ?Sized> !Send for MutexGuard<'_, T> {}
199 #[stable(feature = "mutexguard", since = "1.19.0")]
200 unsafe impl<T: ?Sized + Sync> Sync for MutexGuard<'_, T> {}
201
202 impl<T> Mutex<T> {
203 /// Creates a new mutex in an unlocked state ready for use.
204 ///
205 /// # Examples
206 ///
207 /// ```
208 /// use std::sync::Mutex;
209 ///
210 /// let mutex = Mutex::new(0);
211 /// ```
212 #[stable(feature = "rust1", since = "1.0.0")]
213 pub fn new(t: T) -> Mutex<T> {
214 Mutex {
215 inner: sys::MovableMutex::new(),
216 poison: poison::Flag::new(),
217 data: UnsafeCell::new(t),
218 }
219 }
220
221 /// Immediately drops the guard, and consequently unlocks the mutex.
222 ///
223 /// This function is equivalent to calling [`drop`] on the guard but is more self-documenting.
224 /// Alternately, the guard will be automatically dropped when it goes out of scope.
225 ///
226 /// ```
227 /// #![feature(mutex_unlock)]
228 ///
229 /// use std::sync::Mutex;
230 /// let mutex = Mutex::new(0);
231 ///
232 /// let mut guard = mutex.lock().unwrap();
233 /// *guard += 20;
234 /// Mutex::unlock(guard);
235 /// ```
236 #[unstable(feature = "mutex_unlock", issue = "81872")]
237 pub fn unlock(guard: MutexGuard<'_, T>) {
238 drop(guard);
239 }
240 }
241
242 impl<T: ?Sized> Mutex<T> {
243 /// Acquires a mutex, blocking the current thread until it is able to do so.
244 ///
245 /// This function will block the local thread until it is available to acquire
246 /// the mutex. Upon returning, the thread is the only thread with the lock
247 /// held. An RAII guard is returned to allow scoped unlock of the lock. When
248 /// the guard goes out of scope, the mutex will be unlocked.
249 ///
250 /// The exact behavior on locking a mutex in the thread which already holds
251 /// the lock is left unspecified. However, this function will not return on
252 /// the second call (it might panic or deadlock, for example).
253 ///
254 /// # Errors
255 ///
256 /// If another user of this mutex panicked while holding the mutex, then
257 /// this call will return an error once the mutex is acquired.
258 ///
259 /// # Panics
260 ///
261 /// This function might panic when called if the lock is already held by
262 /// the current thread.
263 ///
264 /// # Examples
265 ///
266 /// ```
267 /// use std::sync::{Arc, Mutex};
268 /// use std::thread;
269 ///
270 /// let mutex = Arc::new(Mutex::new(0));
271 /// let c_mutex = Arc::clone(&mutex);
272 ///
273 /// thread::spawn(move || {
274 /// *c_mutex.lock().unwrap() = 10;
275 /// }).join().expect("thread::spawn failed");
276 /// assert_eq!(*mutex.lock().unwrap(), 10);
277 /// ```
278 #[stable(feature = "rust1", since = "1.0.0")]
279 pub fn lock(&self) -> LockResult<MutexGuard<'_, T>> {
280 unsafe {
281 self.inner.raw_lock();
282 MutexGuard::new(self)
283 }
284 }
285
286 /// Attempts to acquire this lock.
287 ///
288 /// If the lock could not be acquired at this time, then [`Err`] is returned.
289 /// Otherwise, an RAII guard is returned. The lock will be unlocked when the
290 /// guard is dropped.
291 ///
292 /// This function does not block.
293 ///
294 /// # Errors
295 ///
296 /// If another user of this mutex panicked while holding the mutex, then
297 /// this call will return the [`Poisoned`] error if the mutex would
298 /// otherwise be acquired.
299 ///
300 /// If the mutex could not be acquired because it is already locked, then
301 /// this call will return the [`WouldBlock`] error.
302 ///
303 /// [`Poisoned`]: TryLockError::Poisoned
304 /// [`WouldBlock`]: TryLockError::WouldBlock
305 ///
306 /// # Examples
307 ///
308 /// ```
309 /// use std::sync::{Arc, Mutex};
310 /// use std::thread;
311 ///
312 /// let mutex = Arc::new(Mutex::new(0));
313 /// let c_mutex = Arc::clone(&mutex);
314 ///
315 /// thread::spawn(move || {
316 /// let mut lock = c_mutex.try_lock();
317 /// if let Ok(ref mut mutex) = lock {
318 /// **mutex = 10;
319 /// } else {
320 /// println!("try_lock failed");
321 /// }
322 /// }).join().expect("thread::spawn failed");
323 /// assert_eq!(*mutex.lock().unwrap(), 10);
324 /// ```
325 #[stable(feature = "rust1", since = "1.0.0")]
326 pub fn try_lock(&self) -> TryLockResult<MutexGuard<'_, T>> {
327 unsafe {
328 if self.inner.try_lock() {
329 Ok(MutexGuard::new(self)?)
330 } else {
331 Err(TryLockError::WouldBlock)
332 }
333 }
334 }
335
336 /// Determines whether the mutex is poisoned.
337 ///
338 /// If another thread is active, the mutex can still become poisoned at any
339 /// time. You should not trust a `false` value for program correctness
340 /// without additional synchronization.
341 ///
342 /// # Examples
343 ///
344 /// ```
345 /// use std::sync::{Arc, Mutex};
346 /// use std::thread;
347 ///
348 /// let mutex = Arc::new(Mutex::new(0));
349 /// let c_mutex = Arc::clone(&mutex);
350 ///
351 /// let _ = thread::spawn(move || {
352 /// let _lock = c_mutex.lock().unwrap();
353 /// panic!(); // the mutex gets poisoned
354 /// }).join();
355 /// assert_eq!(mutex.is_poisoned(), true);
356 /// ```
357 #[inline]
358 #[stable(feature = "sync_poison", since = "1.2.0")]
359 pub fn is_poisoned(&self) -> bool {
360 self.poison.get()
361 }
362
363 /// Consumes this mutex, returning the underlying data.
364 ///
365 /// # Errors
366 ///
367 /// If another user of this mutex panicked while holding the mutex, then
368 /// this call will return an error instead.
369 ///
370 /// # Examples
371 ///
372 /// ```
373 /// use std::sync::Mutex;
374 ///
375 /// let mutex = Mutex::new(0);
376 /// assert_eq!(mutex.into_inner().unwrap(), 0);
377 /// ```
378 #[stable(feature = "mutex_into_inner", since = "1.6.0")]
379 pub fn into_inner(self) -> LockResult<T>
380 where
381 T: Sized,
382 {
383 let data = self.data.into_inner();
384 poison::map_result(self.poison.borrow(), |_| data)
385 }
386
387 /// Returns a mutable reference to the underlying data.
388 ///
389 /// Since this call borrows the `Mutex` mutably, no actual locking needs to
390 /// take place -- the mutable borrow statically guarantees no locks exist.
391 ///
392 /// # Errors
393 ///
394 /// If another user of this mutex panicked while holding the mutex, then
395 /// this call will return an error instead.
396 ///
397 /// # Examples
398 ///
399 /// ```
400 /// use std::sync::Mutex;
401 ///
402 /// let mut mutex = Mutex::new(0);
403 /// *mutex.get_mut().unwrap() = 10;
404 /// assert_eq!(*mutex.lock().unwrap(), 10);
405 /// ```
406 #[stable(feature = "mutex_get_mut", since = "1.6.0")]
407 pub fn get_mut(&mut self) -> LockResult<&mut T> {
408 let data = self.data.get_mut();
409 poison::map_result(self.poison.borrow(), |_| data)
410 }
411 }
412
413 #[stable(feature = "mutex_from", since = "1.24.0")]
414 impl<T> From<T> for Mutex<T> {
415 /// Creates a new mutex in an unlocked state ready for use.
416 /// This is equivalent to [`Mutex::new`].
417 fn from(t: T) -> Self {
418 Mutex::new(t)
419 }
420 }
421
422 #[stable(feature = "mutex_default", since = "1.10.0")]
423 impl<T: ?Sized + Default> Default for Mutex<T> {
424 /// Creates a `Mutex<T>`, with the `Default` value for T.
425 fn default() -> Mutex<T> {
426 Mutex::new(Default::default())
427 }
428 }
429
430 #[stable(feature = "rust1", since = "1.0.0")]
431 impl<T: ?Sized + fmt::Debug> fmt::Debug for Mutex<T> {
432 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
433 let mut d = f.debug_struct("Mutex");
434 match self.try_lock() {
435 Ok(guard) => {
436 d.field("data", &&*guard);
437 }
438 Err(TryLockError::Poisoned(err)) => {
439 d.field("data", &&**err.get_ref());
440 }
441 Err(TryLockError::WouldBlock) => {
442 struct LockedPlaceholder;
443 impl fmt::Debug for LockedPlaceholder {
444 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
445 f.write_str("<locked>")
446 }
447 }
448 d.field("data", &LockedPlaceholder);
449 }
450 }
451 d.field("poisoned", &self.poison.get());
452 d.finish_non_exhaustive()
453 }
454 }
455
456 impl<'mutex, T: ?Sized> MutexGuard<'mutex, T> {
457 unsafe fn new(lock: &'mutex Mutex<T>) -> LockResult<MutexGuard<'mutex, T>> {
458 poison::map_result(lock.poison.borrow(), |guard| MutexGuard { lock, poison: guard })
459 }
460 }
461
462 #[stable(feature = "rust1", since = "1.0.0")]
463 impl<T: ?Sized> Deref for MutexGuard<'_, T> {
464 type Target = T;
465
466 fn deref(&self) -> &T {
467 unsafe { &*self.lock.data.get() }
468 }
469 }
470
471 #[stable(feature = "rust1", since = "1.0.0")]
472 impl<T: ?Sized> DerefMut for MutexGuard<'_, T> {
473 fn deref_mut(&mut self) -> &mut T {
474 unsafe { &mut *self.lock.data.get() }
475 }
476 }
477
478 #[stable(feature = "rust1", since = "1.0.0")]
479 impl<T: ?Sized> Drop for MutexGuard<'_, T> {
480 #[inline]
481 fn drop(&mut self) {
482 unsafe {
483 self.lock.poison.done(&self.poison);
484 self.lock.inner.raw_unlock();
485 }
486 }
487 }
488
489 #[stable(feature = "std_debug", since = "1.16.0")]
490 impl<T: ?Sized + fmt::Debug> fmt::Debug for MutexGuard<'_, T> {
491 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
492 fmt::Debug::fmt(&**self, f)
493 }
494 }
495
496 #[stable(feature = "std_guard_impls", since = "1.20.0")]
497 impl<T: ?Sized + fmt::Display> fmt::Display for MutexGuard<'_, T> {
498 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
499 (**self).fmt(f)
500 }
501 }
502
503 pub fn guard_lock<'a, T: ?Sized>(guard: &MutexGuard<'a, T>) -> &'a sys::MovableMutex {
504 &guard.lock.inner
505 }
506
507 pub fn guard_poison<'a, T: ?Sized>(guard: &MutexGuard<'a, T>) -> &'a poison::Flag {
508 &guard.lock.poison
509 }