How to do it...

  1. Open the Cargo.toml file that was generated earlier for you.

  2. If you didn't do so in the last recipe, under [dependencies], add the following line:
rayon = "1.0.0"
  1. If you want, you can go to rayon's crates.io page (https://crates.io/crates/rayon) to check for the newest version and use that one instead.
  2. In the folder bin, create a file called join.rs.

  3. Add the following code and run it with cargo run --bin join:

1 extern crate rayon;
2
3 #[derive(Debug)]
4 struct Rectangle {
5 height: u32,
6 width: u32,
7 }
8
9 impl Rectangle {
10 fn area(&self) -> u32 {
11 self.height * self.width
12 }
13 fn perimeter(&self) -> u32 {
14 2 * (self.height + self.width)
15 }
16 }
17
18 fn main() {
19 let rect = Rectangle {
20 height: 30,
21 width: 20,
22 };
23 // rayon::join makes closures run potentially in parallel and
24 // returns their returned values in a tuple
25 let (area, perimeter) = rayon::join(|| rect.area(), ||
rect.perimeter());
26 println!("{:?}", rect);
27 println!("area: {}", area);
28 println!("perimeter: {}", perimeter);
29
30 let fib = fibonacci(6);
31 println!("The sixth number in the fibonacci sequence is {}",
fib);
32 }
33
34 fn fibonacci(n: u32) -> u32 {
35 if n == 0 || n == 1 {
36 n
37 } else {
38 // rayon::join can really shine in recursive functions
39 let (a, b) = rayon::join(|| fibonacci(n - 1), || fibonacci(n
- 2));
40 a + b
41 }
42 }
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.126.211