jitterbug/examples/demo.rs

85 lines
1.8 KiB
Rust
Raw Normal View History

use std::sync::Arc;
use std::task::{Wake, Waker};
2022-01-30 02:26:35 +00:00
use safe_executor::Executor;
2022-01-29 21:50:49 +00:00
2022-01-30 02:26:35 +00:00
fn spawn(runtime: &Executor) {
println!("Spawning futures");
2022-01-29 21:50:49 +00:00
let task1 = runtime.spawn(async move {
println!("Henlo from first spawn");
2022-01-29 21:50:49 +00:00
"A"
});
let task2 = runtime.spawn(async move {
println!("Henlo from second spawn");
2022-01-29 21:50:49 +00:00
"B"
});
let run2m = runtime.clone();
runtime.spawn(async move {
let res1 = task1.await;
let res2 = task2.await;
println!("Henlo from third spawn, {:?}, {:?}", res1, res2);
2022-01-29 21:50:49 +00:00
let res3 = run2m
.spawn(async move {
println!("Henlo from inner spawn");
2022-01-29 21:50:49 +00:00
"D"
})
.await;
println!("Henlo again from third spawn, {:?}", res3);
2022-01-29 21:50:49 +00:00
});
}
struct DummyWaker;
impl Wake for DummyWaker {
fn wake(self: std::sync::Arc<Self>) {}
fn wake_by_ref(self: &Arc<Self>) {}
}
fn main() {
2022-01-30 02:26:35 +00:00
let runtime = Executor::new();
// This creates 3 new tasks
spawn(&runtime);
let waker: Waker = Arc::new(DummyWaker).into();
while runtime.any_woken() {
println!("Ticking");
runtime.tick(&waker);
}
// This reclaims the first 3 tasks
println!("Pruning");
runtime.prune();
2022-01-29 21:50:49 +00:00
// This creates 3 new tasks
spawn(&runtime);
2022-01-29 21:50:49 +00:00
while runtime.any_woken() {
println!("Ticking");
runtime.tick(&waker);
2022-01-29 21:50:49 +00:00
}
// This re-uses the 3 tasks created prior
spawn(&runtime);
// This doesn't reclaim any tasks, since we've spawned 3 more futures
println!("Pruning");
runtime.prune();
while runtime.any_woken() {
println!("Ticking");
runtime.tick(&waker);
// This reclaims tasks as their futures resolve on each tick
println!("Pruning");
runtime.prune();
}
println!("Hewwo Mr Obama");
2022-01-29 21:50:49 +00:00
}