Skip to content

Commit

Permalink
Add rayon example
Browse files Browse the repository at this point in the history
  • Loading branch information
brson committed Jan 23, 2017
1 parent c7fcb91 commit 8c53f12
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 0 deletions.
38 changes: 38 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -638,6 638,44 @@ is why. Rayon provides parallel iterators that make
expressing efficient parallel operations simple
and foolproof.

**Example**: [`examples/rayon.rs`]

[`examples/rayon.rs`]: examples/rayon.rs

```rust
#![allow(unused)]
extern crate rayon;

use rayon::prelude::*;

fn main() {
let mut input = (0..1000).collect::<Vec<_>>();

// Calculate the sum of squares
let sq_sum = input.par_iter()
.map(|&i| i * i)
.sum();

// Increment each element in parallel
input.par_iter_mut()
.for_each(|p| *p = 1);

// Parallel quicksort
let mut input = (0..1000).rev().collect::<Vec<_>>();
quick_sort(&mut input);
}

fn quick_sort<T: PartialOrd Send>(v: &mut [T]) {
if v.len() <= 1 {
return;
}

let mid = v.len() / 2;
let (lo, hi) = v.split_at_mut(mid);
rayon::join(|| quick_sort(lo), || quick_sort(hi));
}
```

&nbsp;&NewLine;&nbsp;&NewLine;&nbsp;&NewLine;


Expand Down
31 changes: 31 additions & 0 deletions examples/rayon.rs
Original file line number Diff line number Diff line change
@@ -0,0 1,31 @@
#![allow(unused)]
extern crate rayon;

use rayon::prelude::*;

fn main() {
let mut input = (0..1000).collect::<Vec<_>>();

// Calculate the sum of squares
let sq_sum = input.par_iter()
.map(|&i| i * i)
.sum();

// Increment each element in parallel
input.par_iter_mut()
.for_each(|p| *p = 1);

// Parallel quicksort
let mut input = (0..1000).rev().collect::<Vec<_>>();
quick_sort(&mut input);
}

fn quick_sort<T: PartialOrd Send>(v: &mut [T]) {
if v.len() <= 1 {
return;
}

let mid = v.len() / 2;
let (lo, hi) = v.split_at_mut(mid);
rayon::join(|| quick_sort(lo), || quick_sort(hi));
}

0 comments on commit 8c53f12

Please sign in to comment.