-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample_fork_join.rs
More file actions
66 lines (63 loc) · 2.39 KB
/
Copy pathexample_fork_join.rs
File metadata and controls
66 lines (63 loc) · 2.39 KB
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
use futures_util::stream::FuturesUnordered;
use futures_util::StreamExt;
use tokio::time::sleep;
use concurrent_tools::concurrent_fork_join::ConcurrentForkJoinTask;
#[tokio::main]
async fn main() {
let count = 100;
{
let (sender, receiver) = kanal::unbounded_async();
tokio::spawn(async move {
for i in 0..count {
sender.send(i).await.unwrap();
}
//sleep(std::time::Duration::from_millis(100)).await;
});
sleep(std::time::Duration::from_millis(1000)).await;
let start = std::time::Instant::now();
let tasks = FuturesUnordered::new();
for i in 0..count {
let recv = receiver.clone();
tasks.push(async move {
let x = recv.recv().await.unwrap();
// simulate computation
std::thread::sleep(std::time::Duration::from_millis(1));
println!("{}", x);
});
}
tasks.collect::<Vec<_>>().await;
let end = std::time::Instant::now();
println!("time taken: {:?}", end.duration_since(start));
}
sleep(std::time::Duration::from_millis(1000)).await;
{
let (sender, receiver) = kanal::unbounded_async();
tokio::spawn(async move {
for i in 0..count {
sender.send(i).await.unwrap();
}
//sleep(std::time::Duration::from_millis(500)).await;
});
sleep(std::time::Duration::from_millis(1000)).await;
let start = std::time::Instant::now();
let mut tasks = Vec::new();
// more task have more opportunity to trigger work stealing but spawn all task have more overhead
for _ in 0..64 {
let receiver = receiver.clone();
let task = tokio::spawn(async move {
ConcurrentForkJoinTask::new(receiver, 4, 1, |x: i32| async move {
// simulate computation
std::thread::sleep(std::time::Duration::from_millis(1));
println!("{}", x);
}).collect::<Vec<_>>().await;
()
});
tasks.push(task);
}
futures_util::stream::iter(tasks)
.for_each_concurrent(None, |it| async move { it.await.unwrap(); })
.await;
let end = std::time::Instant::now();
println!("time taken: {:?}", end.duration_since(start));
}
}