]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys_common/poison.rs
Incorporate a stray test
[rust.git] / src / libstd / sys_common / poison.rs
1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use error::{Error};
12 use fmt;
13 use sync::atomic::{AtomicBool, Ordering};
14 use thread;
15
16 pub struct Flag { failed: AtomicBool }
17
18 // Note that the Ordering uses to access the `failed` field of `Flag` below is
19 // always `Relaxed`, and that's because this isn't actually protecting any data,
20 // it's just a flag whether we've panicked or not.
21 //
22 // The actual location that this matters is when a mutex is **locked** which is
23 // where we have external synchronization ensuring that we see memory
24 // reads/writes to this flag.
25 //
26 // As a result, if it matters, we should see the correct value for `failed` in
27 // all cases.
28
29 impl Flag {
30     pub const fn new() -> Flag {
31         Flag { failed: AtomicBool::new(false) }
32     }
33
34     #[inline]
35     pub fn borrow(&self) -> LockResult<Guard> {
36         let ret = Guard { panicking: thread::panicking() };
37         if self.get() {
38             Err(PoisonError::new(ret))
39         } else {
40             Ok(ret)
41         }
42     }
43
44     #[inline]
45     pub fn done(&self, guard: &Guard) {
46         if !guard.panicking && thread::panicking() {
47             self.failed.store(true, Ordering::Relaxed);
48         }
49     }
50
51     #[inline]
52     pub fn get(&self) -> bool {
53         self.failed.load(Ordering::Relaxed)
54     }
55 }
56
57 pub struct Guard {
58     panicking: bool,
59 }
60
61 /// A type of error which can be returned whenever a lock is acquired.
62 ///
63 /// Both [`Mutex`]es and [`RwLock`]s are poisoned whenever a thread fails while the lock
64 /// is held. The precise semantics for when a lock is poisoned is documented on
65 /// each lock, but once a lock is poisoned then all future acquisitions will
66 /// return this error.
67 ///
68 /// # Examples
69 ///
70 /// ```
71 /// use std::sync::{Arc, Mutex};
72 /// use std::thread;
73 ///
74 /// let mutex = Arc::new(Mutex::new(1));
75 ///
76 /// // poison the mutex
77 /// let c_mutex = mutex.clone();
78 /// let _ = thread::spawn(move || {
79 ///     let mut data = c_mutex.lock().unwrap();
80 ///     *data = 2;
81 ///     panic!();
82 /// }).join();
83 ///
84 /// match mutex.lock() {
85 ///     Ok(_) => unreachable!(),
86 ///     Err(p_err) => {
87 ///         let data = p_err.get_ref();
88 ///         println!("recovered: {}", data);
89 ///     }
90 /// };
91 /// ```
92 ///
93 /// [`Mutex`]: ../../std/sync/struct.Mutex.html
94 /// [`RwLock`]: ../../std/sync/struct.RwLock.html
95 #[stable(feature = "rust1", since = "1.0.0")]
96 pub struct PoisonError<T> {
97     guard: T,
98 }
99
100 /// An enumeration of possible errors associated with a [`TryLockResult`] which
101 /// can occur while trying to acquire a lock, from the [`try_lock`] method on a
102 /// [`Mutex`] or the [`try_read`] and [`try_write`] methods on an [`RwLock`].
103 ///
104 /// [`Mutex`]: struct.Mutex.html
105 /// [`RwLock`]: struct.RwLock.html
106 /// [`TryLockResult`]: type.TryLockResult.html
107 /// [`try_lock`]: struct.Mutex.html#method.try_lock
108 /// [`try_read`]: struct.RwLock.html#method.try_read
109 /// [`try_write`]: struct.RwLock.html#method.try_write
110 #[stable(feature = "rust1", since = "1.0.0")]
111 pub enum TryLockError<T> {
112     /// The lock could not be acquired because another thread failed while holding
113     /// the lock.
114     #[stable(feature = "rust1", since = "1.0.0")]
115     Poisoned(#[stable(feature = "rust1", since = "1.0.0")] PoisonError<T>),
116     /// The lock could not be acquired at this time because the operation would
117     /// otherwise block.
118     #[stable(feature = "rust1", since = "1.0.0")]
119     WouldBlock,
120 }
121
122 /// A type alias for the result of a lock method which can be poisoned.
123 ///
124 /// The [`Ok`] variant of this result indicates that the primitive was not
125 /// poisoned, and the `Guard` is contained within. The [`Err`] variant indicates
126 /// that the primitive was poisoned. Note that the [`Err`] variant *also* carries
127 /// the associated guard, and it can be acquired through the [`into_inner`]
128 /// method.
129 ///
130 /// [`Ok`]: ../../std/result/enum.Result.html#variant.Ok
131 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
132 /// [`into_inner`]: ../../std/sync/struct.PoisonError.html#method.into_inner
133 #[stable(feature = "rust1", since = "1.0.0")]
134 pub type LockResult<Guard> = Result<Guard, PoisonError<Guard>>;
135
136 /// A type alias for the result of a nonblocking locking method.
137 ///
138 /// For more information, see [`LockResult`]. A `TryLockResult` doesn't
139 /// necessarily hold the associated guard in the [`Err`] type as the lock may not
140 /// have been acquired for other reasons.
141 ///
142 /// [`LockResult`]: ../../std/sync/type.LockResult.html
143 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
144 #[stable(feature = "rust1", since = "1.0.0")]
145 pub type TryLockResult<Guard> = Result<Guard, TryLockError<Guard>>;
146
147 #[stable(feature = "rust1", since = "1.0.0")]
148 impl<T> fmt::Debug for PoisonError<T> {
149     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
150         "PoisonError { inner: .. }".fmt(f)
151     }
152 }
153
154 #[stable(feature = "rust1", since = "1.0.0")]
155 impl<T> fmt::Display for PoisonError<T> {
156     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
157         "poisoned lock: another task failed inside".fmt(f)
158     }
159 }
160
161 #[stable(feature = "rust1", since = "1.0.0")]
162 impl<T> Error for PoisonError<T> {
163     fn description(&self) -> &str {
164         "poisoned lock: another task failed inside"
165     }
166 }
167
168 impl<T> PoisonError<T> {
169     /// Creates a `PoisonError`.
170     ///
171     /// This is generally created by methods like [`Mutex::lock`] or [`RwLock::read`].
172     ///
173     /// [`Mutex::lock`]: ../../std/sync/struct.Mutex.html#method.lock
174     /// [`RwLock::read`]: ../../std/sync/struct.RwLock.html#method.read
175     #[stable(feature = "sync_poison", since = "1.2.0")]
176     pub fn new(guard: T) -> PoisonError<T> {
177         PoisonError { guard: guard }
178     }
179
180     /// Consumes this error indicating that a lock is poisoned, returning the
181     /// underlying guard to allow access regardless.
182     ///
183     /// # Examples
184     ///
185     /// ```
186     /// use std::collections::HashSet;
187     /// use std::sync::{Arc, Mutex};
188     /// use std::thread;
189     ///
190     /// let mutex = Arc::new(Mutex::new(HashSet::new()));
191     ///
192     /// // poison the mutex
193     /// let c_mutex = mutex.clone();
194     /// let _ = thread::spawn(move || {
195     ///     let mut data = c_mutex.lock().unwrap();
196     ///     data.insert(10);
197     ///     panic!();
198     /// }).join();
199     ///
200     /// let p_err = mutex.lock().unwrap_err();
201     /// let data = p_err.into_inner();
202     /// println!("recovered {} items", data.len());
203     /// ```
204     #[stable(feature = "sync_poison", since = "1.2.0")]
205     pub fn into_inner(self) -> T { self.guard }
206
207     /// Reaches into this error indicating that a lock is poisoned, returning a
208     /// reference to the underlying guard to allow access regardless.
209     #[stable(feature = "sync_poison", since = "1.2.0")]
210     pub fn get_ref(&self) -> &T { &self.guard }
211
212     /// Reaches into this error indicating that a lock is poisoned, returning a
213     /// mutable reference to the underlying guard to allow access regardless.
214     #[stable(feature = "sync_poison", since = "1.2.0")]
215     pub fn get_mut(&mut self) -> &mut T { &mut self.guard }
216 }
217
218 #[stable(feature = "rust1", since = "1.0.0")]
219 impl<T> From<PoisonError<T>> for TryLockError<T> {
220     fn from(err: PoisonError<T>) -> TryLockError<T> {
221         TryLockError::Poisoned(err)
222     }
223 }
224
225 #[stable(feature = "rust1", since = "1.0.0")]
226 impl<T> fmt::Debug for TryLockError<T> {
227     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
228         match *self {
229             TryLockError::Poisoned(..) => "Poisoned(..)".fmt(f),
230             TryLockError::WouldBlock => "WouldBlock".fmt(f)
231         }
232     }
233 }
234
235 #[stable(feature = "rust1", since = "1.0.0")]
236 impl<T> fmt::Display for TryLockError<T> {
237     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
238         match *self {
239             TryLockError::Poisoned(..) => "poisoned lock: another task failed inside",
240             TryLockError::WouldBlock => "try_lock failed because the operation would block"
241         }.fmt(f)
242     }
243 }
244
245 #[stable(feature = "rust1", since = "1.0.0")]
246 impl<T> Error for TryLockError<T> {
247     fn description(&self) -> &str {
248         match *self {
249             TryLockError::Poisoned(ref p) => p.description(),
250             TryLockError::WouldBlock => "try_lock failed because the operation would block"
251         }
252     }
253
254     fn cause(&self) -> Option<&Error> {
255         match *self {
256             TryLockError::Poisoned(ref p) => Some(p),
257             _ => None
258         }
259     }
260 }
261
262 pub fn map_result<T, U, F>(result: LockResult<T>, f: F)
263                            -> LockResult<U>
264                            where F: FnOnce(T) -> U {
265     match result {
266         Ok(t) => Ok(f(t)),
267         Err(PoisonError { guard }) => Err(PoisonError::new(f(guard)))
268     }
269 }