Can anyone explain async programming with Futures

I read the docs but I don't understand why futures and how it works..

It will be better if u will First create synchronous code then turn that into asynchronous code with futures

I find that this article can be good at giving an initial understanding of how it works. Also, which docs did you read? Did you read the Tokio tutorial?

Yes.

Can u pls provide example with a

synchronous code and turn that into async code with Futures..no async keyword

No async keyword? Using async/await is an important part of async programming.

Assuming you just want more insight into how the Future trait works and might be implemented manually, I have constructed a playground which shows an example of using Futures without the async/await sugar:

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=9d9e6a80296620c6192a26b93b375a6f

This example runs some "timers" concurrently on a single thread.

This example has a number of "gotchas" due to it's simplicity:

  • The playground doesn't show live output, so you'll need to copy it locally to view the timers running properly.
  • There's a lot of syntax noise due to features that aren't relevant in this example, but would be in a bigger program (Wake, Context, Pin, etc).
  • The "executor" is just a loop. Most executors (e.g. tokio) are much smarter about when they poll futures.
2 Likes