I was exploring async/.await and this book explains .await as
Unlike block_on , .await doesn't block the current thread, but instead asynchronously waits for the future to complete, allowing other tasks to run if the future is currently unable to make progress
So to experiement this I wrote below piece of code where I .await multiple futures concurrently using join!() but the o/p of this code confuses my understanding of .await from the book.
#[tokio::main]
async fn main() {
let foo = read_from_console();
let bar = fun();
// .awaiting multiple futures concurrently using join!()
join!(foo,bar);
}
async fn read_from_console() {
let mut line = String::new();
println!("Enter your name :");
std::io::stdin().read_line(&mut line).unwrap();
println!("Hello , {}", line);
}
async fn fun() {
println!("hello from fun");
}
--------------------------------
o/p :
Enter your name :
foo
Hello , foo
hello from fun
---------------------------------
If I go by the book then bar should be allowed to run when foo is still waiting(blocked) for the user input.But here bar is run only after foo is ran into completion. why is it so?
Neither of your functions does anything asynchronous (I/O in the standard library is synchronous), so async-await basically doesn't do anything in your code.
If you switch std::io with tokio::io, you will need .await.
This is because the Tokio version will detect when it would take a long time, and then "task switch" away. The .await keyword indicates that this is expected, and inserts glue code to transform some types which can handle this behavior (e.g. Future).