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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
use antidote::{Mutex, Condvar};
use std::collections::BinaryHeap;
use std::cmp::{PartialOrd, Ord, PartialEq, Eq, Ordering};
use std::sync::Arc;
use std::thread;
use std::time::{Duration, Instant};
use thunk::Thunk;
enum JobType {
Once(Thunk<'static>),
FixedRate {
f: Box<FnMut() + Send + 'static>,
rate: Duration,
},
}
struct Job {
type_: JobType,
time: Instant,
}
impl PartialOrd for Job {
fn partial_cmp(&self, other: &Job) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Job {
fn cmp(&self, other: &Job) -> Ordering {
self.time.cmp(&other.time).reverse()
}
}
impl PartialEq for Job {
fn eq(&self, other: &Job) -> bool {
self.time == other.time
}
}
impl Eq for Job {}
struct InnerPool {
queue: BinaryHeap<Job>,
shutdown: bool,
}
struct SharedPool {
inner: Mutex<InnerPool>,
cvar: Condvar,
}
impl SharedPool {
fn run(&self, job: Job) {
let mut inner = self.inner.lock();
if inner.shutdown {
return;
}
match inner.queue.peek() {
None => self.cvar.notify_all(),
Some(e) if e.time > job.time => self.cvar.notify_all(),
_ => {}
};
inner.queue.push(job);
}
}
pub struct ScheduledThreadPool {
shared: Arc<SharedPool>,
}
impl Drop for ScheduledThreadPool {
fn drop(&mut self) {
self.shared.inner.lock().shutdown = true;
self.shared.cvar.notify_all();
}
}
impl ScheduledThreadPool {
pub fn new(size: usize) -> ScheduledThreadPool {
assert!(size > 0, "size must be positive");
let inner = InnerPool {
queue: BinaryHeap::new(),
shutdown: false,
};
let shared = SharedPool {
inner: Mutex::new(inner),
cvar: Condvar::new(),
};
let pool = ScheduledThreadPool { shared: Arc::new(shared) };
for i in 0..size {
Worker::start(i, pool.shared.clone());
}
pool
}
#[allow(dead_code)]
pub fn run<F>(&self, job: F)
where F: FnOnce() + Send + 'static
{
self.run_after(Duration::from_secs(0), job)
}
pub fn run_after<F>(&self, dur: Duration, job: F)
where F: FnOnce() + Send + 'static
{
let job = Job {
type_: JobType::Once(Thunk::new(job)),
time: Instant::now() + dur,
};
self.shared.run(job)
}
pub fn run_at_fixed_rate<F>(&self, rate: Duration, f: F)
where F: FnMut() + Send + 'static
{
let job = Job {
type_: JobType::FixedRate {
f: Box::new(f),
rate: rate,
},
time: Instant::now() + rate,
};
self.shared.run(job)
}
}
struct Worker {
i: usize,
shared: Arc<SharedPool>,
}
impl Drop for Worker {
fn drop(&mut self) {
if thread::panicking() {
Worker::start(self.i, self.shared.clone());
}
}
}
impl Worker {
fn start(i: usize, shared: Arc<SharedPool>) {
let mut worker = Worker {
i: i,
shared: shared,
};
thread::Builder::new()
.name(format!("r2d2-worker-{}", i))
.spawn(move || worker.run())
.unwrap();
}
fn run(&mut self) {
loop {
match self.get_job() {
Some(job) => self.run_job(job),
None => break,
}
}
}
fn get_job(&self) -> Option<Job> {
enum Need {
Wait,
WaitTimeout(Duration),
}
let mut inner = self.shared.inner.lock();
loop {
let now = Instant::now();
let need = match inner.queue.peek() {
None if inner.shutdown => return None,
None => Need::Wait,
Some(e) if e.time <= now => break,
Some(e) => Need::WaitTimeout(e.time - now),
};
inner = match need {
Need::Wait => self.shared.cvar.wait(inner),
Need::WaitTimeout(t) => self.shared.cvar.wait_timeout(inner, t).0,
};
}
Some(inner.queue.pop().unwrap())
}
fn run_job(&self, job: Job) {
match job.type_ {
JobType::Once(f) => f.invoke(()),
JobType::FixedRate { mut f, rate } => {
f();
let new_job = Job {
type_: JobType::FixedRate { f: f, rate: rate },
time: job.time + rate,
};
self.shared.run(new_job)
}
}
}
}
#[cfg(test)]
mod test {
use std::sync::mpsc::channel;
use std::sync::{Arc, Barrier};
use std::time::Duration;
use super::ScheduledThreadPool;
const TEST_TASKS: usize = 4;
#[test]
fn test_works() {
let pool = ScheduledThreadPool::new(TEST_TASKS);
let (tx, rx) = channel();
for _ in 0..TEST_TASKS {
let tx = tx.clone();
pool.run(move || {
tx.send(1usize).unwrap();
});
}
assert_eq!(rx.iter().take(TEST_TASKS).fold(0, |a, b| a + b), TEST_TASKS);
}
#[test]
#[should_panic(expected = "size must be positive")]
fn test_zero_tasks_panic() {
ScheduledThreadPool::new(0);
}
#[test]
fn test_recovery_from_subtask_panic() {
let pool = ScheduledThreadPool::new(TEST_TASKS);
let waiter = Arc::new(Barrier::new(TEST_TASKS as usize));
for _ in 0..TEST_TASKS {
let waiter = waiter.clone();
pool.run(move || -> () {
waiter.wait();
panic!();
});
}
let (tx, rx) = channel();
let waiter = Arc::new(Barrier::new(TEST_TASKS as usize));
for _ in 0..TEST_TASKS {
let tx = tx.clone();
let waiter = waiter.clone();
pool.run(move || {
waiter.wait();
tx.send(1usize).unwrap();
});
}
assert_eq!(rx.iter().take(TEST_TASKS).fold(0, |a, b| a + b), TEST_TASKS);
}
#[test]
fn test_run_after() {
let pool = ScheduledThreadPool::new(TEST_TASKS);
let (tx, rx) = channel();
let tx1 = tx.clone();
pool.run_after(Duration::from_secs(1), move || tx1.send(1usize).unwrap());
pool.run_after(Duration::from_millis(500), move || tx.send(2usize).unwrap());
assert_eq!(2, rx.recv().unwrap());
assert_eq!(1, rx.recv().unwrap());
}
#[test]
fn test_jobs_complete_after_drop() {
let pool = ScheduledThreadPool::new(TEST_TASKS);
let (tx, rx) = channel();
let tx1 = tx.clone();
pool.run_after(Duration::from_secs(1), move || tx1.send(1usize).unwrap());
pool.run_after(Duration::from_millis(500), move || tx.send(2usize).unwrap());
drop(pool);
assert_eq!(2, rx.recv().unwrap());
assert_eq!(1, rx.recv().unwrap());
}
#[test]
fn test_fixed_delay_jobs_stop_after_drop() {
let pool = Arc::new(ScheduledThreadPool::new(TEST_TASKS));
let (tx, rx) = channel();
let (tx2, rx2) = channel();
let mut pool2 = Some(pool.clone());
let mut i = 0i32;
pool.run_at_fixed_rate(Duration::from_millis(500), move || {
i += 1;
tx.send(i).unwrap();
rx2.recv().unwrap();
if i == 2 {
drop(pool2.take().unwrap());
}
});
drop(pool);
assert_eq!(Ok(1), rx.recv());
tx2.send(()).unwrap();
assert_eq!(Ok(2), rx.recv());
tx2.send(()).unwrap();
assert!(rx.recv().is_err());
}
}