use tokio::time::sleep as Tsleep;
use tokio::time::Duration as TDuration;
async fn async_foo(){
Tsleep(TDuration::from_secs(1)).await;
println!("foo");
}
fn sync_cook(){
std::thread::sleep(std::time::Duration::from_secs(5));
println!("cooking!");
}
#[tokio::main]
async fn main(){
tokio::spawn(async move{
let _ = async_foo();
});
tokio::spawn(async move{
let _ = sync_cook();
});
Tsleep(TDuration::from_secs(5)).await;
}
When I run above code, it only output cooking
once, how to output cooking
and foo
at the same time?
alice
#2
Do not use std::thread::sleep
in async code. Read this for more info.
2 Likes
RobinH
#3
Also, you're missing the .await
for the async_foo()
call
tokio::spawn(async move{
let _ = async_foo().await;
});
Changing that, the program outputs
foo
cooking
1 Like
this is not root cause, if I change the code like:
use tokio::time::sleep as Tsleep;
use tokio::time::Duration as TDuration;
async fn async_foo(){
Tsleep(TDuration::from_secs(2)).await;
println!("foo");
}
fn sync_cook(){
std::thread::sleep(std::time::Duration::from_secs(6));
println!("cooking!");
}
#[tokio::main]
async fn main(){
tokio::spawn(async move{
let _ = async_foo().await;
});
tokio::spawn(async move{
let _ = sync_cook();
});
Tsleep(TDuration::from_secs(1)).await;
}
it still can not output foo
.
cool, thank you very much. 