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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
extern crate crossbeam;
extern crate rand;
mod arena;
mod job;
mod worker;
pub mod iter;
pub use iter::{BorrowSpliterator, BorrowSpliteratorMut, IntoSpliterator, Split, Spliterator};
use crossbeam::sync::chase_lev::deque;
use rand::{Rng, SeedableRng, thread_rng, XorShiftRng};
use self::arena::Arena;
use self::worker::{SharedWorkerData, Worker};
use std::io::Error;
use std::marker::PhantomData;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::thread;
const INITIAL_CAPACITY: usize = 256;
struct WorkerHandle {
thread: Option<thread::JoinHandle<()>>,
}
pub struct Spawner<'pool, 'scope> {
worker: &'pool Worker,
counter: *const AtomicUsize,
_marker: PhantomData<*mut &'scope mut ()>,
}
impl<'pool, 'scope> Spawner<'pool, 'scope> {
pub fn recurse<F>(&self, f: F)
where F: 'scope + Send + FnOnce(&Spawner<'pool, 'scope>)
{
use std::mem;
struct SendCounter(*const AtomicUsize);
unsafe impl Send for SendCounter {}
unsafe {
let counter: SendCounter = SendCounter(self.counter);
if !self.counter.is_null() {
(*self.counter).fetch_add(1, Ordering::AcqRel);
}
self.worker.submit_internal(self.counter, move |worker| {
let SendCounter(count_ptr) = counter;
let spawner = make_spawner(worker, count_ptr);
f(mem::transmute(&spawner))
});
}
}
pub fn submit<F>(&self, f: F) where F: 'scope + Send + FnOnce() {
if !self.counter.is_null() {
unsafe { (*self.counter).fetch_add(1, Ordering::AcqRel) };
}
unsafe {
self.worker.submit_internal(self.counter, move |_| {
f();
});
}
}
pub fn scope<'new, F, R>(&'new self, f: F) -> R
where 'scope: 'new,
F: 'new + FnOnce(&Spawner<'pool, 'new>) -> R,
R: 'new
{
self.worker.scope(f)
}
#[allow(non_camel_case_types)]
pub fn join<A, B, R_A, R_B>(&self, oper_a: A, oper_b: B) -> (R_A, R_B)
where A: Send + for<'new> FnOnce(&Spawner<'pool, 'new>) -> R_A,
B: Send + for<'new> FnOnce(&Spawner<'pool, 'new>) -> R_B,
R_A: Send,
R_B: Send,
{
let mut a_dest = None;
let mut b_dest = None;
self.scope(|scope| {
scope.recurse(|scope| a_dest = Some(oper_a(&scope)));
b_dest = Some(oper_b(&scope));
});
(a_dest.unwrap(), b_dest.unwrap())
}
}
fn make_spawner<'a, 'b>(worker: &'a Worker, counter: *const AtomicUsize) -> Spawner<'a, 'b> {
Spawner {
worker: worker,
counter: counter,
_marker: PhantomData,
}
}
fn worker_main(worker: Worker) {
while !worker.should_shutdown() {
unsafe { worker.run_next(true) };
}
worker.clear();
}
pub struct Pool {
workers: Vec<WorkerHandle>,
local_worker: Worker,
}
impl Pool {
fn new(n: usize) -> Result<Self, Error> {
let (mut poppers, stealers) = {
let mut poppers = Vec::with_capacity(n + 1);
let mut stealers = Vec::with_capacity(n + 1);
for _ in 0..n+1 {
let (p, s) = deque();
poppers.push(p);
stealers.push(s);
}
(poppers.into_iter(), stealers)
};
let mut rng = thread_rng();
let arenas = (0..n + 1).map(|_| Arena::new()).collect::<Vec<_>>();
let shared_data = Arc::new(SharedWorkerData::new(stealers, arenas));
let mut workers = Vec::with_capacity(n);
let local_worker = Worker::new(
shared_data.clone(),
0,
XorShiftRng::from_seed(rng.gen::<[u32; 4]>()),
poppers.next().unwrap(),
);
for (i, pop) in (0..n).zip(poppers) {
let worker = Worker::new(
shared_data.clone(),
i + 1,
XorShiftRng::from_seed(rng.gen::<[u32; 4]>()),
pop,
);
let builder = thread::Builder::new().name(format!("worker_{}", i));
let handle = try!(builder.spawn(move || worker_main(worker)));
workers.push(WorkerHandle {
thread: Some(handle),
});
}
let pool = Pool {
workers: workers,
local_worker: local_worker,
};
Ok(pool)
}
pub fn scope<'pool, 'new, F, R>(&'pool mut self, f: F) -> R
where F: 'new + FnOnce(&Spawner<'pool, 'new>) -> R,
R: 'new,
{
self.local_worker.scope(f)
}
pub fn recurse<'a, F>(&'a mut self, f: F)
where F: 'static + Send + FnOnce(&Spawner<'a, 'static>)
{
self.spawner().recurse(f);
}
pub fn submit<'a, F>(&'a mut self, f: F)
where F: 'static + Send + FnOnce()
{
self.spawner().submit(f);
}
pub fn spawner<'a>(&'a mut self) -> Spawner<'a, 'static> {
use std::ptr;
make_spawner(&self.local_worker, ptr::null_mut())
}
}
impl Drop for Pool {
fn drop(&mut self) {
self.local_worker.shared_data().notify_shutdown();
self.local_worker.clear();
for worker in &mut self.workers {
let handle = worker.thread.take().unwrap();
if handle.join().is_err() {
panic!("Propagating worker thread panic");
}
}
}
}
pub fn make_pool(n: usize) -> Result<Pool, Error> {
Pool::new(n)
}
#[cfg(test)]
fn pool_harness<F>(f: F) where F: Fn(&mut Pool) {
for i in 0..32 {
let mut pool = Pool::new(i).unwrap();
f(&mut pool);
}
}
#[cfg(test)]
mod tests {
use super::{pool_harness, Pool};
#[test]
fn creation_destruction() {
pool_harness(|_| {});
}
#[test]
fn split_work() {
pool_harness(|pool| {
let mut v = vec![0; 1024];
pool.scope(|spawner| {
for (idx, v) in v.iter_mut().enumerate() {
spawner.submit(move || {
*v += idx;
});
}
});
assert_eq!(v, (0..1024).collect::<Vec<_>>());
});
}
#[test]
fn multilevel_scoping() {
pool_harness(|pool| {
pool.scope(|spawner| {
let mut v = vec![0; 256];
spawner.scope(|s| {
for i in &mut v {
s.submit(move || *i += 1)
}
});
assert_eq!(v, vec![1; 256]);
});
});
}
#[test]
fn join() {
pool_harness(|pool| {
let (a, b) = (1, 2);
let (r_a, r_b) = pool.spawner().join(|_| a, |_| b);
assert_eq!(a, r_a);
assert_eq!(b, r_b);
});
}
#[test]
fn join_scoping() {
pool_harness(|pool| {
let mut v = vec![0; 256];
{
let (a, b) = v.split_at_mut(128);
pool.spawner().join(
|_| for i in a { *i += 1},
|_| for i in b { *i += 1},
);
}
assert_eq!(v, vec![1; 256])
});
}
#[test]
fn outlives_pool() {
let v = vec![0; 256];
pool_harness(|pool| {
let mut v = v.clone();
pool.submit(move || {
for i in &mut v {
*i += 1
}
});
});
}
#[test]
fn scope_return() {
pool_harness(|pool| {
let x = pool.scope(|_| 0);
assert_eq!(x, 0);
});
}
#[test]
#[should_panic]
fn job_panic() {
let mut pool = Pool::new(1).unwrap();
pool.submit(|| panic!("Eep!"));
}
#[test]
fn submit_large_jobs() {
pool_harness(|pool| {
let mut v = vec![0; 1024];
pool.scope(|scope| {
let v = &mut v;
let a = [0; 4096];
scope.submit(move || {
let _ = a;
for i in v.iter_mut() { *i += 1 }
});
});
assert_eq!(v, vec![1; 1024]);
});
}
}