1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
use prelude::*;
use cell::UnsafeCell;
use error::FromError;
use fmt;
use thread::Thread;
pub struct Flag { failed: UnsafeCell<bool> }
pub const FLAG_INIT: Flag = Flag { failed: UnsafeCell { value: false } };
impl Flag {
#[inline]
pub fn borrow(&self) -> LockResult<Guard> {
let ret = Guard { panicking: Thread::panicking() };
if unsafe { *self.failed.get() } {
Err(new_poison_error(ret))
} else {
Ok(ret)
}
}
#[inline]
pub fn done(&self, guard: &Guard) {
if !guard.panicking && Thread::panicking() {
unsafe { *self.failed.get() = true; }
}
}
#[inline]
pub fn get(&self) -> bool {
unsafe { *self.failed.get() }
}
}
#[allow(missing_copy_implementations)]
pub struct Guard {
panicking: bool,
}
#[stable]
pub struct PoisonError<T> {
guard: T,
}
#[stable]
pub enum TryLockError<T> {
#[stable]
Poisoned(PoisonError<T>),
#[stable]
WouldBlock,
}
#[stable]
pub type LockResult<Guard> = Result<Guard, PoisonError<Guard>>;
#[stable]
pub type TryLockResult<Guard> = Result<Guard, TryLockError<Guard>>;
impl<T> fmt::Show for PoisonError<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
"poisoned lock: another task failed inside".fmt(f)
}
}
impl<T> PoisonError<T> {
#[stable]
pub fn into_guard(self) -> T { self.guard }
}
impl<T> FromError<PoisonError<T>> for TryLockError<T> {
fn from_error(err: PoisonError<T>) -> TryLockError<T> {
TryLockError::Poisoned(err)
}
}
impl<T> fmt::Show for TryLockError<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
TryLockError::Poisoned(ref p) => p.fmt(f),
TryLockError::WouldBlock => {
"try_lock failed because the operation would block".fmt(f)
}
}
}
}
pub fn new_poison_error<T>(guard: T) -> PoisonError<T> {
PoisonError { guard: guard }
}
pub fn map_result<T, U, F>(result: LockResult<T>, f: F)
-> LockResult<U>
where F: FnOnce(T) -> U {
match result {
Ok(t) => Ok(f(t)),
Err(PoisonError { guard }) => Err(new_poison_error(f(guard)))
}
}