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