⌛ 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 when Poll changes
    • enum Poll<T>:
      • Ready(T) or Pending
Dealing with futures
await
  • .await() -> polls the Future
    • if poll returns Ready(T), the expression will become the value of T
    • if pooll returns Pending, the call will return Pending to the own caller
    • when fn around an await call gets polled again, it will resume at the last await (like JS Generator)
async
  • async keyword before fn or a block {}
    • -> return type of fn will automatically be wrapped in a Future
Helper functions
  • task::block_on(future): polls future until it returns Ready
    • don’t use in async functions (blocks everything)
  • task::spawn_local: adds a Future to a pool that can be polled by block_on
  • task::spawn: adds the async taks to a threadpool, returns JoinHandle that can be awaited for a final value
  • 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