cros_sync_hack/mutex.rs
1// Copyright 2018 The ChromiumOS Authors
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5//! Mutex type whose methods panic rather than returning error in case of
6//! poison.
7//!
8//! The Mutex type in this module wraps the standard library Mutex and mirrors
9//! the same methods, except that they panic where the standard library would
10//! return a PoisonError. This API codifies our error handling strategy around
11//! poisoned mutexes in crosvm.
12//!
13//! - Crosvm releases are built with panic=abort so poisoning never occurs. A
14//! panic while a mutex is held (or ever) takes down the entire process. Thus
15//! we would like for code not to have to consider the possibility of poison.
16//!
17//! - We could ask developers to always write `.lock().unwrap()` on a standard
18//! library mutex. However, we would like to stigmatize the use of unwrap. It
19//! is confusing to permit unwrap but only on mutex lock results. During code
20//! review it may not always be obvious whether a particular unwrap is
21//! unwrapping a mutex lock result or a different error that should be handled
22//! in a more principled way.
23//!
24//! Developers should feel free to use sync::Mutex anywhere in crosvm that they
25//! would otherwise be using std::sync::Mutex.
26
27use std::fmt;
28use std::fmt::Debug;
29use std::fmt::Display;
30use std::sync::Mutex as StdMutex;
31use std::sync::MutexGuard;
32use std::sync::TryLockError;
33
34/// A mutual exclusion primitive useful for protecting shared data.
35#[derive(Default)]
36pub struct Mutex<T: ?Sized> {
37 std: StdMutex<T>,
38}
39
40impl<T> Mutex<T> {
41 /// Creates a new mutex in an unlocked state ready for use.
42 pub fn new(value: T) -> Mutex<T> {
43 Mutex {
44 std: StdMutex::new(value),
45 }
46 }
47
48 /// Consumes this mutex, returning the underlying data.
49 pub fn into_inner(self) -> T {
50 match self.std.into_inner() {
51 Ok(value) => value,
52 Err(_) => panic!("mutex is poisoned"),
53 }
54 }
55}
56
57impl<T: ?Sized> Mutex<T> {
58 /// Acquires a mutex, blocking the current thread until it is able to do so.
59 ///
60 /// This function will block the local thread until it is available to
61 /// acquire the mutex. Upon returning, the thread is the only thread with
62 /// the lock held. An RAII guard is returned to allow scoped unlock of the
63 /// lock. When the guard goes out of scope, the mutex will be unlocked.
64 pub fn lock(&self) -> MutexGuard<T> {
65 match self.std.lock() {
66 Ok(guard) => guard,
67 Err(_) => panic!("mutex is poisoned"),
68 }
69 }
70
71 /// Attempts to acquire this lock.
72 ///
73 /// If the lock could not be acquired at this time, then Err is returned.
74 /// Otherwise, an RAII guard is returned. The lock will be unlocked when the
75 /// guard is dropped.
76 ///
77 /// This function does not block.
78 pub fn try_lock(&self) -> Result<MutexGuard<T>, WouldBlock> {
79 match self.std.try_lock() {
80 Ok(guard) => Ok(guard),
81 Err(TryLockError::Poisoned(_)) => panic!("mutex is poisoned"),
82 Err(TryLockError::WouldBlock) => Err(WouldBlock),
83 }
84 }
85
86 /// Returns a mutable reference to the underlying data.
87 ///
88 /// Since this call borrows the Mutex mutably, no actual locking needs to
89 /// take place -- the mutable borrow statically guarantees no locks exist.
90 pub fn get_mut(&mut self) -> &mut T {
91 match self.std.get_mut() {
92 Ok(value) => value,
93 Err(_) => panic!("mutex is poisoned"),
94 }
95 }
96}
97
98impl<T> From<T> for Mutex<T> {
99 fn from(value: T) -> Self {
100 Mutex {
101 std: StdMutex::from(value),
102 }
103 }
104}
105
106impl<T: ?Sized + Debug> Debug for Mutex<T> {
107 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
108 Debug::fmt(&self.std, formatter)
109 }
110}
111
112/// The lock could not be acquired at this time because the operation would
113/// otherwise block.
114///
115/// Error returned by Mutex::try_lock.
116#[derive(Debug)]
117pub struct WouldBlock;
118
119impl Display for WouldBlock {
120 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
121 Display::fmt(&TryLockError::WouldBlock::<()>, formatter)
122 }
123}
124
125impl std::error::Error for WouldBlock {}