If I create a top-level future inside which I spawn some tasks, those tasks continue to execute even after the call to block_on that drives the top-level future returns:
use tokio::runtime::Runtime;
use tokio::spawn;
use tokio::time::sleep;
use std::time::Duration;
fn main() {
let rt = Runtime::new().unwrap();
rt.block_on(async {
spawn(async {
loop {
println!("a");
sleep(Duration::from_secs(2)).await;
}
});
});
println!("done");
loop {}
}
However tasks spawned using spawn_local seem to stop executing right after block_on returns:
use tokio::runtime::Runtime;
use tokio::task::{spawn_local, LocalSet};
use tokio::time::sleep;
use std::time::Duration;
fn main() {
let rt = Runtime::new().unwrap();
let local = LocalSet::new();
local.block_on(&rt, async {
spawn_local(async {
loop {
println!("a");
sleep(Duration::from_secs(2)).await;
}
});
});
println!("done");
loop {}
}
And the same thing happens with run_until:
use tokio::runtime::Runtime;
use tokio::task::{spawn_local, LocalSet};
use tokio::time::sleep;
use std::time::Duration;
fn main() {
let rt = Runtime::new().unwrap();
let local = LocalSet::new();
rt.block_on(local.run_until(async {
spawn_local(async {
loop {
println!("a");
sleep(Duration::from_secs(2)).await;
}
});
}));
println!("done");
loop {}
}
By the way, async-std seems to behave like tokio in this respect.
So what's the reason for this difference between spawn and spawn_local?