I figured out how to run tokio runtime on the main thread:
use std::time::Duration;
use tokio::{runtime::Builder, sync::oneshot::error::TryRecvError, task::yield_now, time::sleep};
fn main() {
println!("hello");
let rt = Builder::new_current_thread().enable_all().build().unwrap();
let (tx, mut rx) = tokio::sync::oneshot::channel::<()>();
rt.spawn(async {
println!("async, before sleep");
sleep(Duration::from_secs(2)).await;
println!("async, after sleep");
tx.send(()).unwrap();
println!("async, after send");
sleep(Duration::from_secs(0)).await;
println!("async, after second sleep, should not print");
});
loop {
match rx.try_recv() {
Ok(_) => break,
Err(TryRecvError::Empty) => (), // do nothing
Err(TryRecvError::Closed) => panic!("channel closed"),
}
rt.block_on(async {
yield_now().await;
});
}
drop(rt);
println!("after runtime drop");
}