* beginning of an Async section * address review comments * Add futures page (#497) NOTE: `mdbook test` does not allow code samples to reference other crates, so they must be marked as `compile_fail`; see #175. * Add Runtimes & Tasks (#522) These concepts are closely related, and there's not much else to know about runtimes other than "they exist". This removes the bit about futures being "inert" because it doesn't really lead anywhere. * Async chapter (#524) * Add async channels chapter * Async control flow * Async pitfalls * Separate in multiple chapters + add daemon section * Merge reentering threads in blocking-executor * async_trait * Async fixes (#546) * Async: some ideas for simplifying the content (#550) * Simplify the async-await slide * Shorten futures and move it up * Add a page on Tokio * Modifications to the async section (#556) * Modifications to the async section * Remove the "Daemon" slide, as it largely duplicates the "Tasks" slide. The introduction to the "Control Flow" section mentions tasks as a kind of control flow. * Reorganize the structure in SUMMARY.md to correspond to the directory structure. * Simplify the "Pin" and "Blocking the Executor" slides with steps in the speaker notes to demonstrate / fix the issues. * Rename "join_all" to "Join". * Simplify some code samples to shorten them, and to print output rather than asserting. * Clarify speaker notes and include more "Try.." suggestions. * Be consistent about where `async` blocks are introduced (in the "Tasks" slide). * Explain `join` and `select` in prose. * Fix formatting of section-header slides. * Add a note on async trait (#558) --------- Co-authored-by: sakex <alexandre@senges.ch> Co-authored-by: rbehjati <razieh@google.com>
1.2 KiB
async
/await
At a high level, async Rust code looks very much like "normal" sequential code:
use futures::executor::block_on;
async fn count_to(count: i32) {
for i in 1..=count {
println!("Count is: {i}!");
}
}
async fn async_main(count: i32) {
count_to(count).await;
}
fn main() {
block_on(async_main(10));
}
Key points:
-
Note that this is a simplified example to show the syntax. There is no long running operation or any real concurrency in it!
-
What is the return type of an async call?
- Use
let future: () = async_main(10);
inmain
to see the type.
- Use
-
The "async" keyword is syntactic sugar. The compiler replaces the return type with a future.
-
You cannot make
main
async, without additional instructions to the compiler on how to use the returned future. -
You need an executor to run async code.
block_on
blocks the current thread until the provided future has run to completion. -
.await
asynchronously waits for the completion of another operation. Unlikeblock_on
,.await
doesn't block the current thread. -
.await
can only be used inside anasync
function (or block; these are introduced later).