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
// Copyright 2015 Linus Färnstrand
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! # ForkJoin
//! A work stealing fork-join parallelism library.
//!
//! [](https://travis-ci.org/faern/forkjoin)
//!
//! Inspired by the blog post [Data Parallelism in Rust](http://smallcultfollowing.com/babysteps/blog/2013/06/11/data-parallelism-in-rust/)
//! and implemented as part of a master's thesis. Repository hosted at [github.com/faern/forkjoin](https://github.com/faern/forkjoin)
//!
//! Library documentation hosted [here](https://faern.github.io/rust-docs/forkjoin/forkjoin/)
//!
//! This library has been developed to accommodate the needs of three types of
//! algorithms that all fit very well for fork-join parallelism.
//!
//! # Reduce style
//!
//! Reduce style is where the algorithm receive an argument, recursively compute a value
//! from this argument and return one answer. Examples of this style include recursively
//! finding the n:th Fibonacci number and summing of tree structures.
//! Characteristics of this style is that the algorithm does not need to mutate its
//! argument and the resulting value is only available after every subtask has been
//! fully computed.
//!
//! In reduce style algorithms the return values of each subtask is passed to a special
//! join function that is executed when all subtasks have completed.
//! To this join function an extra argument can be sent directly from the task if the algorithm
//! has has `ReduceStyle::Arg`. This can be seen in the examples here.
//!
//! ## Example of reduce style (`ReduceStyle::NoArg`)
//!
//! ```rust
//! use forkjoin::{TaskResult,ForkPool,AlgoStyle,ReduceStyle,Algorithm};
//!
//! fn fib_30_with_4_threads() {
//! let forkpool = ForkPool::with_threads(4);
//! let fibpool = forkpool.init_algorithm(Algorithm {
//! fun: fib_task,
//! style: AlgoStyle::Reduce(ReduceStyle::NoArg(fib_join)),
//! });
//!
//! let job = fibpool.schedule(30);
//! let result: usize = job.recv().unwrap();
//! assert_eq!(1346269, result);
//! }
//!
//! fn fib_task(n: usize, _: usize) -> TaskResult<usize, usize> {
//! if n < 2 {
//! TaskResult::Done(1)
//! } else {
//! TaskResult::Fork(vec![n-1,n-2], None)
//! }
//! }
//!
//! fn fib_join(values: &[usize]) -> usize {
//! values.iter().fold(0, |acc, &v| acc + v)
//! }
//! ```
//!
//! ## Example of reduce style (`ReduceStyle::Arg`)
//!
//! ```rust
//! use forkjoin::{TaskResult,ForkPool,AlgoStyle,ReduceStyle,Algorithm};
//!
//! struct Tree {
//! value: usize,
//! children: Vec<Tree>,
//! }
//!
//! fn sum_tree(t: &Tree) -> usize {
//! let forkpool = ForkPool::new();
//! let sumpool = forkpool.init_algorithm(Algorithm {
//! fun: sum_tree_task,
//! style: AlgoStyle::Reduce(ReduceStyle::Arg(sum_tree_join)),
//! });
//! let job = sumpool.schedule(t);
//! job.recv().unwrap()
//! }
//!
//! fn sum_tree_task(t: &Tree, _: usize) -> TaskResult<&Tree, usize> {
//! if t.children.is_empty() {
//! TaskResult::Done(t.value)
//! } else {
//! let mut fork_args: Vec<&Tree> = vec![];
//! for c in t.children.iter() {
//! fork_args.push(c);
//! }
//! TaskResult::Fork(fork_args, Some(t.value)) // Pass current nodes value to join
//! }
//! }
//!
//! fn sum_tree_seq(t: &Tree) -> usize {
//! t.value + t.children.iter().fold(0, |acc, t2| acc + sum_tree_seq(t2))
//! }
//!
//! fn sum_tree_join(value: &usize, values: &[usize]) -> usize {
//! *value + values.iter().fold(0, |acc, &v| acc + v)
//! }
//! ```
//!
//! # Search style
//!
//! Search style return results continuously and can sometimes start without any
//! argument, or start with some initial state. The algorithm produce one or multiple
//! output values during the execution, possibly aborting anywhere in the middle.
//! Algorithms where leafs in the problem tree represent a complete solution to the
//! problem (unless the leaf represent a dead end that is not a solution and does
//! not spawn any subtasks), for example nqueens and sudoku solvers, have this style.
//! Characteristics of the search style is that they can produce multiple results
//! and can abort before all tasks in the tree have been computed.
//!
//! ## Example of search style
//!
//! ```rust
//! use forkjoin::{ForkPool,TaskResult,AlgoStyle,Algorithm};
//!
//! type Queen = usize;
//! type Board = Vec<Queen>;
//! type Solutions = Vec<Board>;
//!
//! fn search_nqueens() {
//! let n: usize = 8;
//! let empty = vec![];
//!
//! let forkpool = ForkPool::with_threads(4);
//! let queenpool = forkpool.init_algorithm(Algorithm {
//! fun: nqueens_task,
//! style: AlgoStyle::Search,
//! });
//!
//! let job = queenpool.schedule((empty, n));
//!
//! let mut solutions: Vec<Board> = vec![];
//! loop {
//! match job.recv() {
//! Err(..) => break, // Job has completed
//! Ok(board) => solutions.push(board),
//! };
//! }
//! let num_solutions = solutions.len();
//! println!("Found {} solutions to nqueens({}x{})", num_solutions, n, n);
//! }
//!
//! fn nqueens_task((q, n): (Board, usize), _: usize) -> TaskResult<(Board,usize), Board> {
//! if q.len() == n {
//! TaskResult::Done(q)
//! } else {
//! let mut fork_args: Vec<(Board, usize)> = vec![];
//! for i in 0..n {
//! let mut q2 = q.clone();
//! q2.push(i);
//!
//! if ok(&q2[..]) {
//! fork_args.push((q2, n));
//! }
//! }
//! TaskResult::Fork(fork_args, None)
//! }
//! }
//!
//! fn ok(q: &[usize]) -> bool {
//! for (x1, &y1) in q.iter().enumerate() {
//! for (x2, &y2) in q.iter().enumerate() {
//! if x2 > x1 {
//! let xd = x2-x1;
//! if y1 == y2 || y1 == y2 + xd || (y2 >= xd && y1 == y2 - xd) {
//! return false;
//! }
//! }
//! }
//! }
//! true
//! }
//! ```
//!
//! # In-place mutation style
//!
//! NOTE: This style works in the current lib version, but it requires very ugly
//! unsafe code!
//!
//! In-place mutation style receive a mutable argument, recursively modifies this value
//! and the result is the argument itself. Sorting algorithms that sort their input
//! arrays are cases of this style. Characteristics of this style is that they mutate
//! their input argument instead of producing any output.
//!
//! Examples of this will come when they can be nicely implemented.
//!
//! # Tasks
//!
//! The small units that are executed and can choose to fork or to return a value is the
//! `TaskFun`. A TaskFun can NEVER block, because that would block the kernel thread
//! it's being executed on. Instead it should decide if it's done calculating or need
//! to fork. This decision is taken in the return value to indicate to the user
//! that a TaskFun need to return before anything can happen.
//!
//! A TaskFun return a `TaskResult`. It can be `TaskResult::Done(value)` if it's done
//! calculating. It can be `TaskResult::Fork(args)` if it needs to fork.
//!
//! # TODO
//!
//! - [ ] Make mutation style algorithms work without giving join function
//! - [ ] Implement a sorting algorithm. Quicksort?
//! - [ ] Remove need to return None on fork with NoArg
//! - [ ] Make it possible to use algorithms with different Arg & Ret on same pool.
//! - [ ] Make ForkJoin work in stable Rust.
//! - [ ] Remove mutex around channel in search style.
extern crate deque;
extern crate rand;
extern crate num_cpus;
extern crate libc;
use Unique;
use AtomicUsize;
use ;
use ;
use fmt;
use thread;
use ;
/// Type definition of the main function in a task.
/// Your task functions must have this signature
pub type TaskFun<Arg, Ret> = extern "Rust" fn ;
/// Type definition of functions joining together forked results.
/// Only used in `AlgoStyle::Reduce` algorithms with `ReduceStyle::NoArg`.
pub type TaskJoin<Ret> = extern "Rust" fn ;
/// Similar to `TaskJoin` but takes an extra argument sent directly
/// from the task in algorithms with `ReduceStyle::Arg`.
pub type TaskJoinArg<Ret> = extern "Rust" fn ;
/// Internal representation of a task.
/// Return values from tasks. Represent a computed value or a fork of the algorithm.
/// Enum representing the style of the executed algorithm.
/// Enum indicating what type of join function an `Algorithm` will use.
/// The representation of a specific algorithm to use the ForkJoin library.
///
/// Create one instance of this struct for each algorithm to be executed in ForkJoin.
/// Internal struct for receiving results from multiple subtasks in parallel
/// Enum describing what to do with results of `Task`s and `JoinBarrier`s.
/// Enum indicating there was a problem fetching a result from a job.
/// The handle for a computation. Can be used to fetch results of the computation.
/// Upon drop it will wait for the entire computation to complete if it's still executing.
/// Algorithm termination is detected by the `try_recv` and `recv` methods returning a `ResultError`
/// A handle for a specific `Algorithm` running on a `ForkPool`.
/// Acquired from `ForkPool::init_algorithm`.
/// Main struct of the ForkJoin library.
/// Represents a pool of threads implementing a work stealing algorithm.