Implement Future
Contract
- Future is a regular trait which has a method
poll pollshould returnPoll::Ready(...)if you think theFuturecomplets.pollshould returnPoll::Pendingif you think theFutureis in progresspollis initially invoked underneath by the async runtime.- You need to tell the async runtime to invoke
pollagain if yourFutureis in progress. Otherwise, it never complete.
We will use tokio as the async runtime.
Poll::Ready
The program completes immediately.
Poll::Pending
The program never stop.
How do we tell the async runtime invoke poll again?
Use Waker
busy polling
The program keeps polling.
cx.waker().wake_by_ref();final complete
Finally, the program needs return Poll::Ready.
interval polling
The program keeps interval polling using a thread.
Use OS mechanism
Thread spawning is not costless. We could use OS timer somehow, but it’s a bit of complex to setup OS layer. Luckily, tokio Sleep has already been implemented for us.
-
We declare a heap-allocated pointer first, then convert that to a Pin pointer.
-
We declare a Pin pointer directly using
Box::pinwhich is typePin<Box<T>>.Pin<Box<T>>could be converted toPin<&mut T>using itsBox::as_mutmethod.
For how to use Pin, see pin