⌛ Rust Async
Concepts
Futures
= an operation that can be tested for completion
std::future::Future
- trait
Future
:fn poll (cx)
->Poll<Self::Output>
cx
: callback for whenPoll
changes
- enum
Poll<T>
:Ready(T)
orPending
- trait
Dealing with futures
await
.await()
-> polls theFuture
- if poll returns
Ready(T)
, the expression will become the value of T - if pooll returns
Pending
, the call will returnPending
to the own caller - when fn around an
await
call gets polled again, it will resume at the lastawait
(like JS Generator)
- if poll returns
async
async
keyword beforefn
or a block{}
- -> return type of
fn
will automatically be wrapped in aFuture
- -> return type of
Helper functions
task::block_on(future)
: polls future until it returnsReady
- don’t use in
async
functions (blocks everything)
- don’t use in
task::spawn_local
: adds aFuture
to a pool that can be polled byblock_on
task::spawn
: adds the async taks to a threadpool, returnsJoinHandle
that can be awaited for a final value- Future to pass must implement
send
(🤹 Rust Concurrency)
- Future to pass must implement
task::yield_now()
: add a breakpoint to an async function- used to occasionally break from long async functions to avoid blocking
task::spawn_blocking
: moves async function to separate thread