⌛ 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 whenPollchanges
- 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 returnPendingto the own caller - when fn around an
awaitcall gets polled again, it will resume at the lastawait(like JS Generator)
- if poll returns
async
asynckeyword beforefnor a block{}- -> return type of
fnwill automatically be wrapped in aFuture
- -> return type of
Helper functions
task::block_on(future): polls future until it returnsReady- don’t use in
asyncfunctions (blocks everything)
- don’t use in
task::spawn_local: adds aFutureto a pool that can be polled byblock_ontask::spawn: adds the async taks to a threadpool, returnsJoinHandlethat 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