forked from constellation-rs/constellation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfibonacci.rs
95 lines (87 loc) · 1.87 KB
/
fibonacci.rs
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
use constellation::*;
use futures::future::join;
use serde_closure::FnOnce;
use serde_traitobject as st;
fn fib_threads(x: usize) -> usize {
if x <= 1 {
return x;
}
let a = std::thread::spawn(move || fib_threads(x - 1));
let b = std::thread::spawn(move || fib_threads(x - 2));
let a = a.join().unwrap();
let b = b.join().unwrap();
a + b
}
fn fib_processes(x: usize) -> usize {
if x <= 1 {
return x;
}
let left_pid = spawn(
Resources::default(),
FnOnce!(move |parent_pid| {
Sender::<usize>::new(parent_pid)
.send(fib_processes(x - 1))
.block()
}),
)
.block()
.unwrap();
let right_pid = spawn(
Resources::default(),
FnOnce!(move |parent_pid| {
Sender::<usize>::new(parent_pid)
.send(fib_processes(x - 2))
.block()
}),
)
.block()
.unwrap();
Receiver::<usize>::new(left_pid).recv().block().unwrap()
+ Receiver::<usize>::new(right_pid).recv().block().unwrap()
}
fn fib_processes_async(x: usize) -> Result<usize, Box<dyn st::Error>> {
type Msg = Result<usize, Box<dyn st::Error>>;
if x <= 1 {
return Ok(x);
}
let left = async {
let pid = spawn(
Resources::default(),
FnOnce!(move |parent| {
Sender::<Msg>::new(parent)
.send(fib_processes_async(x - 1))
.block()
}),
)
.await?;
let receiver = Receiver::<Msg>::new(pid);
receiver.recv().await?
};
let right = async {
let pid = spawn(
Resources::default(),
FnOnce!(move |parent| {
Sender::<Msg>::new(parent)
.send(fib_processes_async(x - 2))
.block()
}),
)
.await?;
let receiver = Receiver::<Msg>::new(pid);
receiver.recv().await?
};
let (left, right) = join(left, right).block();
Ok(left? + right?)
}
fn main() {
init(Resources::default());
for i in 0..10 {
println!("{}", fib_threads(i));
}
for i in 0..10 {
println!("{}", fib_processes(i));
}
for i in 0..10 {
println!("{}", fib_processes_async(i).unwrap());
}
}