Construct a Rust Async runtime (basic) that polls a list of futures using…
- User
Construct a Rust Async runtime (basic) that polls a list of futures using
std::task::ContextandWaker. Assistant
Construct a Rust Async runtime (basic) that polls a list of futures using std::task::Context and Waker.
The user wants to build a basic asynchronous runtime in Rust. The core requirements are:
std::task::Context and Waker.tokio or async-std, just the standard library).Key Components of an Async Runtime:
std::future::Future. The runtime needs to drive these to completion.std::task::Wake trait or using std::task::Waker::from_raw (unsafe) or, easier for a simple example, using an Arc<Waker> pattern. Actually, the standard library provides std::task::Wake for a safe implementation.Context, and calls poll.epoll/kqueuefrom scratch. However, to demonstrateWakercorrectly, I need a scenario wherePending` is returned and then later woken up.Strategy:
Task: A wrapper around a future. Since futures are often moved, I need to pin them. A common pattern is Box<dyn Future>.Waker source: I need a struct that implements the Wake trait. This struct will likely hold a flag or a notification channel to tell the executor to re-poll. For a basic example, an AtomicBool or a simple counter stored in an Arc is easiest.block_on function: This is the entry point. It takes a main future (or a list of them) and runs until they are done.Waker from my Wake implementation.Context from the Waker.future.poll(cx).Ready, return/finish.Pending, wait (sleep/yield) and repeat.Refining the "List of Futures" requirement:
The user specifically said "polls a list of futures". This implies a multi-task executor, not just block_on on a single future.
So, I need a queue of tasks.
Vec of pinned, boxed futures.Context without complex event loops.AtomicBool inside its waker. The executor only polls tasks where the flag is true (or just polls everything if any flag is true).For a "basic" educational implementation, Approach A (Iterate all) is the easiest to understand, but Approach B (Waker sets a flag) demonstrates the purpose of the Waker better.
Let's go with a hybrid: A simple executor that holds a list of tasks. Each task has a future and a flag indicating if it's "ready".
Actually, let's keep it strictly minimal. std::future::Future requires Pinning.
Step-by-Step Implementation Plan:
std::future::Future, std::pin::Pin, std::task::{Context, Poll, Waker, Wake}, std::sync::Arc, std::thread, std::time::*.Task Struct: Needs to hold the future. Since Rust futures are state machines, and we need to store them in a collection, they must be pinned and boxed.
type Task = Pin<Box<dyn Future<Output = ()> + Send>>; (Using () output for simplicity).Waker Implementation:
We need a way to wake up the specific task.
Let's define a TaskNode that holds an AtomicBool.
The Wake implementation sets this bool to true.(Waker, Task).spawn method: Adds a future to the list.run method:
Pending, leave it in the list.Ready, remove it from the list.Refining the Waker Logic:
How do we create a Waker? std::task::Waker. We need to implement ArcWake logic manually or use Wake trait. In modern stable Rust, we can use std::task::Wake on an Arc struct.
Let's define:
struct TaskWaker {
ready: AtomicBool,
}
impl Wake for TaskWaker {
fn wake(self: Arc<Self>) {
self.ready.store(true, Ordering::Relaxed);
}
}
The "Timer" Example:
To prove it works, I need a future that isn't ready immediately. A Timer future is the standard example.
TimerFuture: holds a Instant and a Thread handle?
Actually, a standard Timer future usually spawns a thread or uses a reactor. Since we don't have a reactor, the simplest Timer future just checks Instant::now() inside poll.
Wait, if the Timer future checks time inside poll, the runtime must poll it repeatedly to detect the time change.
This is a "busy" runtime.
To make it less busy, thread::sleep can be used in the main loop, but that reduces responsiveness.
For a "basic" runtime, checking time in poll is fine.
Wait, is the "Wake" logic strictly necessary for a busy-loop? If I just loop over the list constantly:
loop {
for task in tasks {
task.poll();
}
}
I technically don't strictly need the Waker to do anything useful other than exist, because the runtime polls regardless. However, the prompt specifically asks to use Context and Waker. I should demonstrate how the waker would work in a non-busy loop, or at least how it fits into the API.
Better approach: The Executor sleeps if no tasks are "awake".
The Wake implementation sets a flag. The executor checks the flag.
However, passing the specific waker to the specific task is the tricky part of manual runtime implementation.
Revised Plan for "Task" abstraction:
Let's define a Task wrapper that holds the Future AND the Arc<AtomicBool> (the wake-up state).
AtomicWaker wrapper:
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::task::Wake;
struct TaskWaker {
is_ready: AtomicBool,
}
impl Wake for TaskWaker {
fn wake(self: Arc<Self>) {
self.is_ready.store(true, Ordering::Release);
}
}
Executor:
A Vec of structs containing the Future and the Arc<TaskWaker>.
The Loop:
Iterate through the vec.
If is_ready is false, skip? No, initial poll needs to happen.
Create Waker from Arc<TaskWaker>.
Create Context.
Poll.
If Pending: set is_ready to false (it was consumed/will be set by external event).
If Ready: Remove from list.
Handling the Timer Example to show Async behavior:
I will create a Timer future.
This future checks the time. If time isn't up, it returns Pending.
Ideally, the Timer future registers itself with some "System" to be woken up.
Since we don't have a system reactor, the simplest way to simulate async IO is:
The Timer future spawns a thread on creation. The thread sleeps for X seconds. Then it calls waker.wake().
Code structure for Timer:
struct Timer {
wake_time: Instant,
// We need to hold the waker or have a channel? No, the runtime passes waker in poll.
// But to wake from a thread, we need to store the waker.
// This gets complex quickly for a "basic" example.
}
Simpler Timer: Just check the time in poll.
If Instant::now() < wake_time, return Pending.
Otherwise Ready.
This requires the runtime to poll repeatedly (busy loop).
Alternative: Just build the executor to poll repeatedly. This satisfies "polls a list of futures". The Waker is passed to the context, but the logic relies on the fact that the runtime doesn't sleep.
Let's refine the "Basic" aspect.
If I implement the Wake trait, I can use Waker::from(waker_arc).
I will create an Executor struct.
It holds tasks: Vec<Task>.
Task holds future and waker_data.
Let's write the code mentally:
Critique of the "Basic" approach:
If the user writes a future like async { 1 + 1 }, it finishes immediately.
If the user writes async { Timer::new(1 sec).await; }, that Timer must wake the executor.
If Timer just returns Pending without calling wake(), my runtime (as sketched above) will hang because ready is false.
To make a robust "Basic" runtime that handles both:
wake? No.Let's stick to the "Spin" approach for the runtime loop (it's "basic"), but we will implement the Wake trait correctly so the futures could use it to optimize, or simply rely on the loop.
Wait, the prompt asks to use Waker. I should construct the Context correctly.
I will implement a Timer future that utilizes the Waker to demonstrate the integration. The Timer will spawn a thread (simulating an IO event) that calls waker.wake().
Final Plan:
Task struct: Holds the future and an Arc<AtomicBool> for wake-up state.Wake impl: Sets the AtomicBool to true.Executor:
spawn: Adds tasks.block_on: The loop.
Waker and Context.Pending, check if waker was called?The Code Structure:
Timer future that waits for a duration. It spawns a thread to call wake().Executor using std::task.Let's refine the Timer logic.
If I create a future Timer, and I poll it, I get a Context with a Waker.
I can clone the waker and move it to a thread.
thread::spawn(move || { sleep; waker.wake(); });
Then I return Pending.
The runtime sees Pending.
The runtime waits...
The thread finishes, calls wake().
wake() sets the task's flag to true.
The runtime loop sees the flag, polls again -> Ready.
This perfectly demonstrates the interaction.
Corner Case in Task List:
We need Pin<Box<dyn Future<Output = T> + Send>>.
I will assume output () for simplicity.
Safety:
Implementing Wake on an Arc struct is safe.
Creating Context is safe.
Let's write the code.
Save this code in a main.rs file.
Task: We wrap a Future in an Arc<Mutex<Pin<Box<...>>>>. This allows the executor to own the future, share it with the waker, and safely pin it in memory.Waker: Rust's Context requires a Waker. We create a struct TaskWaker that implements the Wake trait.
TimerFuture) completes its background work, it calls waker.wake().wake simply pushes the task back into the ready_queue.Executor Loop:
Context containing the Waker.future.poll(cx).Pending: The future saves the waker and waits. The executor moves on.Ready: The task is done and removed.TimerFuture:
poll, it is not done. It returns Pending and saves the Waker.completed = true and calls waker.wake().completed is true, and returns Ready.use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll, Wake, Waker};
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::{Duration, Instant};
// 1. Define the Waker mechanism
// We need a flag to know if the task should be polled.
struct TaskMeta {
// We use a Mutex or AtomicBool. AtomicBool is faster.
ready: std::sync::atomic::AtomicBool,
}
impl Wake for TaskMeta {
fn wake(self: Arc<Self>) {
self.ready.store(true, std::sync::atomic::Ordering::Relaxed);
}
}
// 2. Define the Executor
struct Executor {
tasks: Vec<(Arc<TaskMeta>, Pin<Box<dyn Future<Output = ()> + Send>>)>,
}
impl Executor {
fn spawn(&mut self, future: impl Future<Output = ()> + Send + 'static) {
let meta = Arc::new(TaskMeta {
ready: std::sync::atomic::AtomicBool::new(true), // Initially ready to run
});
self.tasks.push((meta, Box::pin(future)));
}
fn run(&mut self) {
// Loop until all tasks are done
while !self.tasks.is_empty() {
// We need to drain/iter carefully because we remove finished tasks
let mut i = 0;
while i < self.tasks.len() {
let (meta, future) = &mut self.tasks[i];
// Optimization: Only poll if ready flag is set
// Note: For a busy-loop timer, this flag might not be needed,
// but it demonstrates Waker usage.
// However, if we rely strictly on wake(), a pure CPU-bound task
// might never wake itself if it returns Pending without scheduling a wake.
// Let's assume for this basic runtime, we ALWAYS poll if not finished,
// to support "check time" futures.
// But to show Waker usage, let's use the flag.
// Actually, simpler: Just poll everything.
// But that's not really "Async" runtime, that's just a loop.
// Let's use the flag approach.
if meta.ready.load(std::sync::atomic::Ordering::Relaxed) {
// Reset flag before poll? Or after?
// If we reset before, and poll returns Pending,
// we assume the future took responsibility for waking.
meta.ready.store(false, std::sync::atomic::Ordering::Relaxed);
let waker = Waker::from(meta.clone());
let mut cx = Context::from_waker(&waker);
match future.as_mut().poll(&mut cx) {
Poll::Ready(()) => {
self.tasks.remove(i);
continue; // Don't increment i
}
Poll::Pending => {
// Future is not done. It *should* have arranged for `wake` to be called.
// If it didn't (e.g. simple timer check), we might starve.
// To handle simple timers without a reactor,
// we can force `ready` to true periodically or loop infinitely.
}
}
}
i += 1;
}
// Prevent CPU melting if all tasks are sleeping
thread::yield_now();
}
}
}
use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll, Waker, Wake};
use std::thread;
use std::time::{Duration, Instant};
// ------------------------------------------------------------------------------------------------
// 1. The Task Wrapper
// ------------------------------------------------------------------------------------------------
/// A wrapper around a Future that allows it to be rescheduled.
/// We use a Mutex to allow shared ownership during polling.
type Task = Arc<Mutex<Pin<Box<dyn Future<Output = ()> + Send + 'static>>>>;
// ------------------------------------------------------------------------------------------------
// 2. The Waker Implementation
// ------------------------------------------------------------------------------------------------
/// A simple struct that implements the `Wake` trait.
/// This is the bridge between the event (like a timer finishing) and the executor.
struct TaskWaker {
task: Task,
}
impl Wake for TaskWaker {
fn wake(self: Arc<Self>) {
// When `wake` is called, we simply re-add the task to the executor's queue.
// This signals that the task is ready to make progress.
EXECUTOR.with(|e| e.enqueue(self.task.clone()));
}
}
// ------------------------------------------------------------------------------------------------
// 3. The Executor (Singleton for simplicity)
// ------------------------------------------------------------------------------------------------
/// A very basic global executor.
thread_local! {
static EXECUTOR: Executor = Executor::new();
}
struct Executor {
// A list of tasks ready to be polled.
// We use a simple Vec as a queue.
ready_queue: Mutex<Vec<Task>>,
}
impl Executor {
fn new() -> Self {
Self {
ready_queue: Mutex::new(Vec::new()),
}
}
/// Adds a new task to the queue.
fn spawn(&self, future: impl Future<Output = ()> + Send + 'static) {
let task = Arc::new(Mutex::new(Box::pin(future)));
self.enqueue(task);
}
fn enqueue(&self, task: Task) {
let mut queue = self.ready_queue.lock().unwrap();
queue.push(task);
}
/// The main event loop.
fn run(&self) {
loop {
// 1. Take a task from the queue (if any)
let task = {
let mut queue = self.ready_queue.lock().unwrap();
queue.pop()
};
match task {
Some(task) => {
// 2. Create a Waker for this task
let waker = Arc::new(TaskWaker { task: task.clone() }).into();
let mut cx = Context::from_waker(&waker);
// 3. Lock the future and poll it
// We use `try_lock` to avoid deadlock if the waker is called synchronously
// inside the future, though a simple mutex lock usually works for this example.
let mut future = task.lock().unwrap();
match future.as_mut().poll(&mut cx) {
Poll::Ready(()) => {
// Task finished, do nothing (drop it)
println!("Task finished.");
}
Poll::Pending => {
// Task is waiting. Do nothing here.
// The Waker is responsible for putting it back in the queue later.
}
}
}
None => {
// Queue empty. In a real runtime, we would wait for IO events (epoll/kqueue).
// Here, we just sleep a bit to avoid burning 100% CPU in a spin loop.
thread::sleep(Duration::from_millis(10));
}
}
}
}
}
// ------------------------------------------------------------------------------------------------
// 4. A Demo Future (Timer)
// ------------------------------------------------------------------------------------------------
/// A future that waits for a specific duration.
/// It uses a separate thread to simulate an async IO event.
struct TimerFuture {
shared_state: Arc<Mutex<TimerState>>,
}
struct TimerState {
completed: bool,
waker: Option<Waker>,
}
impl TimerFuture {
fn new(duration: Duration) -> Self {
let shared_state = Arc::new(Mutex::new(TimerState {
completed: false,
waker: None,
}));
// Spawn a thread to do the "work"
let thread_shared_state = shared_state.clone();
thread::spawn(move || {
thread::sleep(duration);
let mut state = thread_shared_state.lock().unwrap();
state.completed = true;
if let Some(waker) = state.waker.take() {
waker.wake(); // <--- This triggers the TaskWaker::wake method
}
});
Self { shared_state }
}
}
impl Future for TimerFuture {
type Output = ();
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let mut state = self.shared_state.lock().unwrap();
if state.completed {
Poll::Ready(())
} else {
// Save the waker so the timer thread can use it later.
state.waker = Some(cx.waker().clone());
Poll::Pending
}
}
}
// ------------------------------------------------------------------------------------------------
// 5. Main Entry Point
// ------------------------------------------------------------------------------------------------
fn main() {
EXECUTOR.with(|e| {
// Spawn two timers to run concurrently on the same thread
e.spawn(async {
println!("Start Task 1 (2s)...");
TimerFuture::new(Duration::from_secs(2)).await;
println!("End Task 1!");
});
e.spawn(async {
println!("Start Task 2 (1s)...");
TimerFuture::new(Duration::from_secs(1)).await;
println!("End Task 2!");
});
// Start the loop
e.run();
});
}