Tokio

Tokio provides:

  • A multi-threaded runtime for executing asynchronous code.
  • An asynchronous version of the standard library.
  • A large ecosystem of libraries.
  1. use tokio::time;
  2. async fn count_to(count: i32) {
  3.     for i in 0..count {
  4.         println!("Count in task: {i}!");
  5.         time::sleep(time::Duration::from_millis(5)).await;
  6.     }
  7. }
  8. #[tokio::main]
  9. async fn main() {
  10.     tokio::spawn(count_to(10));
  11.     for i in 0..5 {
  12.         println!("Main task: {i}");
  13.         time::sleep(time::Duration::from_millis(5)).await;
  14.     }
  15. }
  • With the tokio::main macro we can now make main async.

  • The spawn function creates a new, concurrent “task”.

  • Note: spawn takes a Future, you don’t call .await on count_to.

Further exploration:

  • Why does count_to not (usually) get to 10? This is an example of async cancellation. tokio::spawn returns a handle which can be awaited to wait until it finishes.

  • Try count_to(10).await instead of spawning.

  • Try awaiting the task returned from tokio::spawn.