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
326
327
328
329
330
331
332
#![deny(missing_docs)]
extern crate crossbeam;
#[macro_use]
extern crate futures;
extern crate num_cpus;
use std::panic::{self, AssertUnwindSafe};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::thread;
use crossbeam::sync::MsQueue;
use futures::{IntoFuture, Future, oneshot, Oneshot, Complete, Poll, Async};
use futures::task::{self, Run, Executor};
pub struct CpuPool {
inner: Arc<Inner>,
}
pub struct Builder {
pool_size: usize,
after_start: Option<Arc<Fn() + Send + Sync>>,
before_stop: Option<Arc<Fn() + Send + Sync>>,
}
struct Sender<F, T> {
fut: F,
tx: Option<Complete<T>>,
}
fn _assert() {
fn _assert_send<T: Send>() {}
fn _assert_sync<T: Sync>() {}
_assert_send::<CpuPool>();
_assert_sync::<CpuPool>();
}
struct Inner {
queue: MsQueue<Message>,
cnt: AtomicUsize,
size: usize,
after_start: Option<Arc<Fn() + Send + Sync>>,
before_stop: Option<Arc<Fn() + Send + Sync>>,
}
#[must_use]
pub struct CpuFuture<T, E> {
inner: Oneshot<thread::Result<Result<T, E>>>,
}
enum Message {
Run(Run),
Close,
}
impl CpuPool {
pub fn new(size: usize) -> CpuPool {
Builder::new().pool_size(size).create()
}
pub fn new_num_cpus() -> CpuPool {
Builder::new().create()
}
pub fn spawn<F>(&self, f: F) -> CpuFuture<F::Item, F::Error>
where F: Future + Send + 'static,
F::Item: Send + 'static,
F::Error: Send + 'static,
{
let (tx, rx) = oneshot();
let sender = Sender {
fut: AssertUnwindSafe(f).catch_unwind(),
tx: Some(tx),
};
task::spawn(sender).execute(self.inner.clone());
CpuFuture { inner: rx }
}
pub fn spawn_fn<F, R>(&self, f: F) -> CpuFuture<R::Item, R::Error>
where F: FnOnce() -> R + Send + 'static,
R: IntoFuture + 'static,
R::Future: Send + 'static,
R::Item: Send + 'static,
R::Error: Send + 'static,
{
self.spawn(futures::lazy(f))
}
}
fn work(inner: &Inner) {
inner.after_start.as_ref().map(|fun| fun());
loop {
match inner.queue.pop() {
Message::Run(r) => r.run(),
Message::Close => break,
}
}
inner.before_stop.as_ref().map(|fun| fun());
}
impl Clone for CpuPool {
fn clone(&self) -> CpuPool {
self.inner.cnt.fetch_add(1, Ordering::Relaxed);
CpuPool { inner: self.inner.clone() }
}
}
impl Drop for CpuPool {
fn drop(&mut self) {
if self.inner.cnt.fetch_sub(1, Ordering::Relaxed) == 1 {
for _ in 0..self.inner.size {
self.inner.queue.push(Message::Close);
}
}
}
}
impl Executor for Inner {
fn execute(&self, run: Run) {
self.queue.push(Message::Run(run))
}
}
impl<T: Send + 'static, E: Send + 'static> Future for CpuFuture<T, E> {
type Item = T;
type Error = E;
fn poll(&mut self) -> Poll<T, E> {
match self.inner.poll().expect("shouldn't be canceled") {
Async::Ready(Ok(Ok(e))) => Ok(e.into()),
Async::Ready(Ok(Err(e))) => Err(e),
Async::Ready(Err(e)) => panic::resume_unwind(e),
Async::NotReady => Ok(Async::NotReady),
}
}
}
impl<F: Future> Future for Sender<F, Result<F::Item, F::Error>> {
type Item = ();
type Error = ();
fn poll(&mut self) -> Poll<(), ()> {
if let Ok(Async::Ready(_)) = self.tx.as_mut().unwrap().poll_cancel() {
return Ok(().into())
}
let res = match self.fut.poll() {
Ok(Async::Ready(e)) => Ok(e),
Ok(Async::NotReady) => return Ok(Async::NotReady),
Err(e) => Err(e),
};
self.tx.take().unwrap().complete(res);
Ok(Async::Ready(()))
}
}
impl Builder {
pub fn new() -> Builder {
Builder {
pool_size: num_cpus::get(),
after_start: None,
before_stop: None,
}
}
pub fn pool_size(&mut self, size: usize) -> &mut Self {
self.pool_size = size;
self
}
pub fn after_start<F>(&mut self, f: F) -> &mut Self
where F: Fn() + Send + Sync + 'static
{
self.after_start = Some(Arc::new(f));
self
}
pub fn before_stop<F>(&mut self, f: F) -> &mut Self
where F: Fn() + Send + Sync + 'static
{
self.before_stop = Some(Arc::new(f));
self
}
pub fn create(&mut self) -> CpuPool {
let pool = CpuPool {
inner: Arc::new(Inner {
queue: MsQueue::new(),
cnt: AtomicUsize::new(1),
size: self.pool_size,
after_start: self.after_start.clone(),
before_stop: self.before_stop.clone(),
}),
};
assert!(self.pool_size > 0);
for _ in 0..self.pool_size {
let inner = pool.inner.clone();
thread::spawn(move || work(&inner));
}
return pool
}
}