Why Async?
Pros
Asynchronous allows concurrent operation on the same thread. Multi-threaded code requires a lot of overhead and resources, even with minimal implementations.
Cons
Threads are natively supported and managed by the operating system, whereas async code is a language-specific implementation. Using async code also involves more complexity.
async
/.await
Primer
async
trnasforms a block of code into a state machine that implements the Future
trait. A blocked Future
will yield control of the thread.
Concept: Async code can only run via the use of an executor. Invoking an async function will do nothing if its
Future
is not given to an executor likeblock_on
.
block_on
is the simplest executor. Others have more complex behavior, like scheduling multiple futures. Note it does block the current thread.
use futures::executor::block_on; async fn hello_async() { println!("Hello, async!"); } fn main() { let future = hello_async(); // this will do nothing but return the Future block_on(future); }