Understanding Futures

Hello, i am trying to understand futures in rust since so long, i just am not able to grasp the barebones of how futures works under the hood, and what if i want to create my own futures from scratch for some library i am creating. can anyone explain with coding example , a very simple example.

How to use park and unpark methods ?

When we sending NotReady response in Poll, how to keep track of callers, so when poll is ready to response, how it should response and stuff.

i really really really am interested in this stuff, just need to have that barebone knowledge of this stuff.

thank you rust community, you guys are amazing.

2 Likes

This is probably a large topic to cover, but I have an older example I came up with for futures called promiser, before I saw any future libraries.

Specifically, on Wait I submit the thread-id to a channel and then park that thread
https://github.com/viperscape/rust-promise/blob/master/src/promise.rs#L149-L152

When the delivering thread is ready to wake up Waiting threads, it signals them with an unpark by reading the thread-id channel for any threads to wake.
https://github.com/viperscape/rust-promise/blob/master/src/promise.rs#L114-L118

Hope this helps! I'm sure there are many other ways to tackle this concept

1 Like

You should offer a Futures example for the Rust Cookbook:

https://brson.github.io/rust-cookbook/
https://github.com/brson/rust-cookbook/

@dtolnay, what do you think?

I trust you have read the official tutorials, they are very high quality for such young libraries!

Futures is built for async I/O, and async I/O means using tokio. When implementing your own future, usually you will poll another future to determine if it's ready, all the way down to using a tokio primitive such as TcpStream which will call task::park() and schedule unparking for you.

By spawning the future in an executor such as a tokio Core, an Unpark implementation will be provided so that the future is scheduled to be polled on the Core upon being unparked.

If you are curious about how everything fits together or want to roll your own executor or park/unpark system, the flow goes something like this:

future is polled and is not ready -> future calls task::park() and somehow sets up the returned handle to be unparked on an event -> future returns NotReady -> the event happens and unpark is called on the handle -> unpark schedules the future to be polled again on the event loop -> the event loop polls the future and everything starts over.

1 Like