top | item 42271479

(no title)

vbsd | 1 year ago

> because `tokio::time::sleep()` keeps track of when the future was created, (ie when `sleep()` was called) instead of when the future is first `.await`ed

I’m not a Rust programmer but I strongly suspect this updated explanation is erroneous. It’s probably more like this: start time is recorded when the task execution is started. However, the task immediately yields control back to the async loop. Then the async loop starts another task, and so on. It’s just that the async loop only returns the control to sleeping task no earlier than the moment 1s passes after the task execution was initialy started. I’d be surprised if it had anything to do with when sleep() was called.

discuss

order

davidatbu|1 year ago

Someone linked the code in another comment, and the start time is most definitely recorded when the future is created: https://docs.rs/tokio/1.41.1/src/tokio/time/sleep.rs.html#12...

vbsd|1 year ago

Huh, you're right about this, thanks.

On the other hand, I maintain that this is an incidental rather than essential reason for the program finishing quickly. In that benchmark code, we can replace "sleep" with our custom sleep function which does not record start time before execution:

  async fn wrapped_sleep(d: Duration) {
      sleep(d).await
  }

The following program will still finish in ~10 seconds.

  #[tokio::main]
  async fn main() {
      let num_tasks = 100;
      let mut tasks = Vec::new();
      for _ in 0..num_tasks {
          tasks.push(wrapped_sleep(Duration::from_secs(10)));
      }
      futures::future::join_all(tasks).await;
  }