Skip to content

Commit 58c3a35

Browse files
committed
add rayon examples
1 parent 98a0908 commit 58c3a35

File tree

3 files changed

+97
-1
lines changed

3 files changed

+97
-1
lines changed

rayon_examples/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,3 +6,4 @@ edition = "2021"
66
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
77

88
[dependencies]
9+
rayon = "1.5.3"

rayon_examples/src/lib.rs

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
use rayon::prelude::*;
2+
3+
pub fn rayon_par_iter() {
4+
let v = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
5+
let sum = v.par_iter().map(|x| x * x).sum::<i32>();
6+
println!("sum: {}", sum);
7+
8+
let mut left = vec![42; 10];
9+
let mut right = vec![-1; 10];
10+
11+
(10..15)
12+
.into_par_iter()
13+
.enumerate()
14+
.unzip_into_vecs(&mut left, &mut right);
15+
16+
assert_eq!(left, [0, 1, 2, 3, 4]);
17+
assert_eq!(right, [10, 11, 12, 13, 14]);
18+
}
19+
20+
pub fn rayon_scope_example() {
21+
rayon::scope(|s| {
22+
s.spawn(|_| {
23+
println!("Hello from a thread!");
24+
});
25+
});
26+
}
27+
28+
pub fn rayon_scope_example2() {
29+
let mut value_a = None;
30+
let mut value_b = None;
31+
let mut value_c = None;
32+
rayon::scope(|s| {
33+
s.spawn(|s1| {
34+
value_a = Some(22);
35+
36+
s1.spawn(|_| {
37+
value_b = Some(44);
38+
});
39+
});
40+
41+
s.spawn(|_| {
42+
value_c = Some(66);
43+
});
44+
});
45+
assert_eq!(value_a, Some(22));
46+
assert_eq!(value_b, Some(44));
47+
assert_eq!(value_c, Some(66));
48+
}
49+
50+
51+
pub fn rayon_scopefifo_example() {
52+
rayon::scope_fifo(|s| {
53+
s.spawn_fifo(|s| { // task s.1
54+
println!("s.1");
55+
s.spawn_fifo(|_s| { // task s.1.1
56+
println!("s.1.1");
57+
rayon::scope_fifo(|t| {
58+
t.spawn_fifo(|_| println!("t.1")); // task t.1
59+
t.spawn_fifo(|_| println!("t.2")); // task t.2
60+
});
61+
});
62+
});
63+
s.spawn_fifo(|_s| { // task s.2
64+
println!("s.2");
65+
});
66+
// point mid
67+
});
68+
}
69+
70+
pub fn rayon_threadpool_example() {
71+
fn fib(n: usize) -> usize {
72+
if n == 0 || n == 1 {
73+
return n;
74+
}
75+
let (a, b) = rayon::join(|| fib(n - 1), || fib(n - 2)); // runs inside of `pool`
76+
return a + b;
77+
}
78+
79+
let pool = rayon::ThreadPoolBuilder::new()
80+
.num_threads(4)
81+
.build()
82+
.unwrap();
83+
84+
let n = pool.install(|| fib(20));
85+
86+
println!("{}", n);
87+
}

rayon_examples/src/main.rs

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,11 @@
1+
2+
use rayon_examples::*;
3+
14
fn main() {
2-
println!("Hello, world!");
5+
rayon_par_iter();
6+
7+
rayon_scope_example();
8+
rayon_scope_example2();
9+
rayon_scopefifo_example();
10+
rayon_threadpool_example();
311
}

0 commit comments

Comments
 (0)