Future Trait in Rust

The Future trait in Rust is a fundamental component of asynchronous programming. It represents an asynchronous computation that will eventually produce a value. This trait is essential for writing non-blocking code, allowing developers to handle operations that may take time, such as I/O operations, without freezing the entire program.

Definition and Structure

The Future trait is defined as follows:

pub trait Future {
    type Output;
    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>;
}

Components of the Future Trait

  • Output Type: The Output type is the result of the computation once the future is complete.
  • Poll Method: The poll method is used by the async runtime to check if the computation is complete. It returns either Poll::Pending if the computation is not yet complete, or Poll::Ready(val) if the computation has finished and produced a value.

Implementing Custom Futures

Creating a custom future involves defining a type that implements the Future trait, specifying the output type, and providing a poll method. This method determines if the future is ready to produce a value or if it should be polled again later.

Example: Custom Future with Async Timer

Below is an example of implementing a custom future using an async timer:

use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::{Duration, Instant};

struct AsyncTimer {
    expiration_time: Instant,
}

impl Future for AsyncTimer {
    type Output = String;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        if Instant::now() >= self.expiration_time {
            println!("Hello, it's time for Future 1");
            Poll::Ready(String::from("Future 1 has completed"))
        } else {
            println!("Hello, it's not yet time for Future 1. Going to sleep");
            let waker = cx.waker().clone();
            let expiration_time = self.expiration_time;
            std::thread::spawn(move || {
                let current_time = Instant::now();
                if current_time < expiration_time {
                    std::thread::sleep(expiration_time - current_time);
                }
                waker.wake();
            });
            Poll::Pending
        }
    }
}

Explanation

  • Pinning: Futures need to be pinned to a specific memory location to ensure safe execution. This is achieved using the Pin type.
  • Context and Waker: The Context provides the context of the async task, including a Waker that can be used to wake the task when it is ready to be polled again.
  • Poll Method: The poll method checks if the current time has reached the expiration time. If so, it returns Poll::Ready with a message. Otherwise, it sets up a thread to wake the task when the time is right and returns Poll::Pending.

Figures Illustrating Custom Futures

[Figure 10.7: Implementing a Custom Future](https://livebook.manning.com/book/rust-servers-services-and-apps/chapter-10/140)

Figure 10.7 Implementing a custom future Figure 10.7 Implementing a custom future

[Figure 10.8: Spawning Async Tasks with Futures](https://livebook.manning.com/book/rust-servers-services-and-apps/chapter-10/140)

Figure 10.8 Spawning async tasks with futures, step 1 Figure 10.8 Spawning async tasks with futures, step 1

[Figure 10.9: Writing a Future with a Waker Component](https://livebook.manning.com/book/rust-servers-services-and-apps/chapter-10/140)

Figure 10.9 Writing a future with a waker component, step 2 Figure 10.9 Writing a future with a waker component, step 2

[Figure 10.11: Custom Future with Poll::Ready](https://livebook.manning.com/book/rust-servers-services-and-apps/chapter-10/140)

Figure 10.11 Custom future with Poll::Ready, step 3 Figure 10.11 Custom future with Poll::Ready, step 3

[Figure 10.12: Custom Future with Expiration Time](https://livebook.manning.com/book/rust-servers-services-and-apps/chapter-10/189)

Figure 10.12 Custom future with expiration time, step 4 Figure 10.12 Custom future with expiration time, step 4

These figures illustrate the process of implementing and using custom futures in Rust, showcasing the interaction between the poll method, the Waker, and the async runtime.

FAQ (Frequently asked questions)

What does the poll method return in the Future trait?

How does the async timer inform the async runtime executor to reschedule the task?