-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgeneric.rs
294 lines (267 loc) · 8.23 KB
/
generic.rs
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
extern crate parking_lot;
extern crate ordermap;
extern crate chrono;
use std::usize::MAX as USIZE_MAX;
use std::result::Result;
use std::mem::transmute;
use std::sync::Arc;
use std::time::{Duration, Instant};
use self::parking_lot::{Condvar, Mutex, RwLock};
use self::ordermap::OrderMap;
use self::chrono::Duration as ChDuration;
pub struct Event {
mutex: Mutex<bool>,
condvar: Condvar,
auto_reset: bool,
map: RwLock<OrderMap<MutexKey, CondvarWithId>>,
}
#[derive(PartialEq, Eq, Hash)]
struct MutexKey {
mutex: * const Mutex<usize>,
}
unsafe impl Send for MutexKey {}
unsafe impl Sync for MutexKey {}
struct CondvarWithId {
condvar: * const Condvar,
id: usize,
kind: WaitFor,
}
unsafe impl Send for CondvarWithId {}
unsafe impl Sync for CondvarWithId {}
enum WaitFor {
Any,
All,
}
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct WaitTimeoutResult {
timed_out: bool,
}
impl WaitTimeoutResult {
pub fn timed_out(&self) -> bool {
self.timed_out
}
}
impl From<parking_lot::WaitTimeoutResult> for WaitTimeoutResult {
fn from(wtr: parking_lot::WaitTimeoutResult) -> Self {
WaitTimeoutResult { timed_out: wtr.timed_out() }
}
}
impl Event {
pub fn new(initial_signaled: bool, auto_reset: bool) -> Result<Self, ()> {
Ok(Event {
mutex: Mutex::new(initial_signaled),
condvar: Condvar::new(),
auto_reset: auto_reset,
map: RwLock::new(OrderMap::new()),
})
}
pub fn wait(&self) {
let mut guard = self.mutex.lock();
if !*guard {
self.condvar.wait(&mut guard);
assert!(*guard == true);
};
if self.auto_reset {
*guard = false;
};
}
pub fn wait_for(&self, timeout: Duration) -> WaitTimeoutResult {
if ChDuration::from_std(timeout.clone()).unwrap_or_else(|_e| {
panic!("Time period too large.");
}).num_milliseconds() < 0 {
panic!("Cannot wait for a negative time period.");
};
self.wait_until(Instant::now() + timeout)
}
pub fn wait_until(&self, timeout: Instant) -> WaitTimeoutResult {
if timeout < Instant::now() {
panic!("Cannot wait for a previous time.");
};
let mut ret_value = WaitTimeoutResult { timed_out: false };
let mut guard = self.mutex.lock();
if !*guard {
let result = self.condvar.wait_until(&mut guard, timeout);
ret_value = WaitTimeoutResult::from(result);
assert!(*guard == true || ret_value.timed_out());
};
if self.auto_reset {
*guard = false;
};
ret_value
}
pub fn notify(&self) {
let mut guard = self.mutex.lock();
*guard = true;
self.condvar.notify_all();
let map = self.map.read();
if map.len() != 0 {
for (key, value) in map.iter() {
let mutex = unsafe { key.mutex.as_ref().unwrap() };
let condvar = unsafe { value.condvar.as_ref().unwrap() };
let mut guard = mutex.lock();
match value.kind {
WaitFor::Any => *guard = value.id,
WaitFor::All => *guard += value.id,
};
condvar.notify_all();
};
};
}
pub fn unnotify(&self) {
let mut guard = self.mutex.lock();
*guard = false;
}
}
pub fn wait_for_any_with(slice: &[Arc<Event>], timeout: Duration) ->
Result<usize, WaitTimeoutResult>
{
if ChDuration::from_std(timeout.clone()).unwrap_or_else(|_e| {
panic!("Time period too large.");
}).num_milliseconds() < 0 {
panic!("Cannot wait for a negative time period.");
};
wait_for_any_until_impl(slice, true, Instant::now() + timeout)
}
pub fn wait_for_any_until(slice: &[Arc<Event>], timeout: Instant) ->
Result<usize, WaitTimeoutResult>
{
if timeout < Instant::now() {
panic!("Cannot wait for a previous time.");
};
wait_for_any_until_impl(slice, true, timeout)
}
pub fn wait_for_any(slice: &[Arc<Event>]) -> usize {
wait_for_any_until_impl(slice, false, Instant::now()).unwrap()
}
fn wait_for_any_until_impl(
slice: &[Arc<Event>],
with_timeout: bool,
timeout: Instant
) -> Result<usize, WaitTimeoutResult> {
let mutex = Mutex::new(USIZE_MAX);
let condvar = Condvar::new();
let mutex_ptr = &mutex as * const Mutex<usize>;
let condvar_ptr = &condvar as * const Condvar;
let key = MutexKey { mutex: mutex_ptr };
let id;
let result;
{
let mut guard = mutex.lock();
for (id, event_ref) in slice.iter().enumerate() {
let guard2 = event_ref.mutex.lock();
if *guard2 {
for i in 0..id {
let mut map = slice.get(i).unwrap().map.write();
map.remove(&key);
};
return Ok(id);
};
let mut map = event_ref.map.write();
map.insert(
MutexKey { mutex: mutex_ptr },
CondvarWithId {
condvar: condvar_ptr,
id: id,
kind: WaitFor::Any
}
);
};
result = if with_timeout {
let mut result = unsafe {
transmute::<bool, parking_lot::WaitTimeoutResult>(false)
};
while *guard == USIZE_MAX && !result.timed_out() {
result = condvar.wait_until(&mut guard, timeout.clone());
};
id = *guard;
result.timed_out()
} else {
while *guard == USIZE_MAX {
condvar.wait(&mut guard);
};
id = *guard;
false
};
};
for event_ref in slice.iter() {
let mut map = event_ref.map.write();
map.remove(&key);
};
if result {
Err(WaitTimeoutResult { timed_out: true })
} else {
Ok(id)
}
}
pub fn wait_for_all_with(slice: &[Arc<Event>], timeout: Duration) ->
WaitTimeoutResult
{
if ChDuration::from_std(timeout.clone()).unwrap_or_else(|_e| {
panic!("Time period too large.");
}).num_milliseconds() < 0 {
panic!("Cannot wait for a negative time period.");
};
wait_for_all_until_impl(slice, true, Instant::now() + timeout)
}
pub fn wait_for_all_until(slice: &[Arc<Event>], timeout: Instant) ->
WaitTimeoutResult
{
if timeout < Instant::now() {
panic!("Cannot wait for a previous time.");
};
wait_for_all_until_impl(slice, true, timeout)
}
pub fn wait_for_all(slice: &[Arc<Event>]) {
wait_for_all_until_impl(slice, false, Instant::now());
}
fn wait_for_all_until_impl(
slice: &[Arc<Event>],
with_timeout: bool,
timeout: Instant
) -> WaitTimeoutResult {
let mutex = Mutex::new(0usize);
let condvar = Condvar::new();
let mutex_ptr = &mutex as * const Mutex<usize>;
let condvar_ptr = &condvar as * const Condvar;
let from_all = (slice.len() * (slice.len() + 1)) / 2;
let result;
{
let mut guard = mutex.lock();
for (id, event_ref) in slice.iter().enumerate() {
let guard2 = event_ref.mutex.lock();
if *guard2 {
*guard += id + 1;
continue;
};
let mut map = event_ref.map.write();
map.insert(
MutexKey { mutex: mutex_ptr },
CondvarWithId {
condvar: condvar_ptr,
id: id + 1,
kind: WaitFor::All
}
);
};
result = if with_timeout {
let mut result = unsafe {
transmute::<bool, parking_lot::WaitTimeoutResult>(false)
};
while *guard != from_all && !result.timed_out() {
result = condvar.wait_until(&mut guard, timeout.clone());
};
result.timed_out()
} else {
while *guard != from_all {
condvar.wait(&mut guard);
};
false
};
};
let key = MutexKey { mutex: mutex_ptr };
for event_ref in slice.iter() {
let mut map = event_ref.map.write();
map.remove(&key);
};
WaitTimeoutResult { timed_out: result }
}