]> git.lizzy.rs Git - rust.git/blob - src/libstd/sync/poison.rs
d7fcee3ae2e527df7229c1c2a11a6ad7900f9700
[rust.git] / src / libstd / sync / 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 prelude::v1::*;
12
13 use cell::UnsafeCell;
14 use error::{Error, FromError};
15 use fmt;
16 use thread::Thread;
17
18 pub struct Flag { failed: UnsafeCell<bool> }
19 pub const FLAG_INIT: Flag = Flag { failed: UnsafeCell { value: false } };
20
21 impl Flag {
22     #[inline]
23     pub fn borrow(&self) -> LockResult<Guard> {
24         let ret = Guard { panicking: Thread::panicking() };
25         if unsafe { *self.failed.get() } {
26             Err(new_poison_error(ret))
27         } else {
28             Ok(ret)
29         }
30     }
31
32     #[inline]
33     pub fn done(&self, guard: &Guard) {
34         if !guard.panicking && Thread::panicking() {
35             unsafe { *self.failed.get() = true; }
36         }
37     }
38
39     #[inline]
40     pub fn get(&self) -> bool {
41         unsafe { *self.failed.get() }
42     }
43 }
44
45 #[allow(missing_copy_implementations)]
46 pub struct Guard {
47     panicking: bool,
48 }
49
50 /// A type of error which can be returned whenever a lock is acquired.
51 ///
52 /// Both Mutexes and RwLocks are poisoned whenever a task fails while the lock
53 /// is held. The precise semantics for when a lock is poisoned is documented on
54 /// each lock, but once a lock is poisoned then all future acquisitions will
55 /// return this error.
56 #[stable]
57 pub struct PoisonError<T> {
58     guard: T,
59 }
60
61 /// An enumeration of possible errors which can occur while calling the
62 /// `try_lock` method.
63 #[stable]
64 pub enum TryLockError<T> {
65     /// The lock could not be acquired because another task failed while holding
66     /// the lock.
67     #[stable]
68     Poisoned(PoisonError<T>),
69     /// The lock could not be acquired at this time because the operation would
70     /// otherwise block.
71     #[stable]
72     WouldBlock,
73 }
74
75 /// A type alias for the result of a lock method which can be poisoned.
76 ///
77 /// The `Ok` variant of this result indicates that the primitive was not
78 /// poisoned, and the `Guard` is contained within. The `Err` variant indicates
79 /// that the primitive was poisoned. Note that the `Err` variant *also* carries
80 /// the associated guard, and it can be acquired through the `into_inner`
81 /// method.
82 #[stable]
83 pub type LockResult<Guard> = Result<Guard, PoisonError<Guard>>;
84
85 /// A type alias for the result of a nonblocking locking method.
86 ///
87 /// For more information, see `LockResult`. A `TryLockResult` doesn't
88 /// necessarily hold the associated guard in the `Err` type as the lock may not
89 /// have been acquired for other reasons.
90 #[stable]
91 pub type TryLockResult<Guard> = Result<Guard, TryLockError<Guard>>;
92
93 #[stable]
94 impl<T> fmt::Debug for PoisonError<T> {
95     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
96         "PoisonError { inner: .. }".fmt(f)
97     }
98 }
99
100 #[stable]
101 impl<T> fmt::Display for PoisonError<T> {
102     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
103         self.description().fmt(f)
104     }
105 }
106
107 impl<T> Error for PoisonError<T> {
108     fn description(&self) -> &str {
109         "poisoned lock: another task failed inside"
110     }
111 }
112
113 impl<T> PoisonError<T> {
114     /// Consumes this error indicating that a lock is poisoned, returning the
115     /// underlying guard to allow access regardless.
116     #[deprecated="renamed to into_inner"]
117     pub fn into_guard(self) -> T { self.guard }
118
119     /// Consumes this error indicating that a lock is poisoned, returning the
120     /// underlying guard to allow access regardless.
121     #[unstable]
122     pub fn into_inner(self) -> T { self.guard }
123
124     /// Reaches into this error indicating that a lock is poisoned, returning a
125     /// reference to the underlying guard to allow access regardless.
126     #[unstable]
127     pub fn get_ref(&self) -> &T { &self.guard }
128
129     /// Reaches into this error indicating that a lock is poisoned, returning a
130     /// mutable reference to the underlying guard to allow access regardless.
131     #[unstable]
132     pub fn get_mut(&mut self) -> &mut T { &mut self.guard }
133 }
134
135 impl<T> FromError<PoisonError<T>> for TryLockError<T> {
136     fn from_error(err: PoisonError<T>) -> TryLockError<T> {
137         TryLockError::Poisoned(err)
138     }
139 }
140
141 #[stable]
142 impl<T> fmt::Debug for TryLockError<T> {
143     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
144         match *self {
145             TryLockError::Poisoned(..) => "Poisoned(..)".fmt(f),
146             TryLockError::WouldBlock => "WouldBlock".fmt(f)
147         }
148     }
149 }
150
151 #[stable]
152 impl<T> fmt::Display for TryLockError<T> {
153     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
154         self.description().fmt(f)
155     }
156 }
157
158 impl<T> Error for TryLockError<T> {
159     fn description(&self) -> &str {
160         match *self {
161             TryLockError::Poisoned(ref p) => p.description(),
162             TryLockError::WouldBlock => "try_lock failed because the operation would block"
163         }
164     }
165
166     fn cause(&self) -> Option<&Error> {
167         match *self {
168             TryLockError::Poisoned(ref p) => Some(p),
169             _ => None
170         }
171     }
172 }
173
174 pub fn new_poison_error<T>(guard: T) -> PoisonError<T> {
175     PoisonError { guard: guard }
176 }
177
178 pub fn map_result<T, U, F>(result: LockResult<T>, f: F)
179                            -> LockResult<U>
180                            where F: FnOnce(T) -> U {
181     match result {
182         Ok(t) => Ok(f(t)),
183         Err(PoisonError { guard }) => Err(new_poison_error(f(guard)))
184     }
185 }