
Recall first from Why async and the Future trait
- One hart can interleave independent I/O tasks when each task returns control while it waits.
- Future::poll receives a pinned mutable reference and a task context, and returns Poll<Self::Output>.
- Pending means the operation is unfinished, and Ready carries its final output.
What a wake requests
3 min readThe last lesson defined Future. Now you build a waker by hand with the RawWakerVTable, the piece std hides but no_std must write, and honor its memory-safety contract.
A Linux program that waits for activity on file descriptors can use epoll to receive readiness notifications. For a readable socket, the program still has to perform the read. The course kernel faces a related problem inside its own async runtime. Once a future has returned Poll::Pending, how will the runtime know when to check it again? Here the notification is a Rust Waker call made by code that knows the task should get another poll. epoll(7): the epoll interface
The executor gives the future a Context when it polls it. cx.waker() returns a shared reference to the waker for that task. You will often hear the operation described as “call cx.waker().wake().” In actual Rust, wake takes ownership of the waker, so the two valid forms depend on what you hold:
cx.waker().wake_by_ref(); // Request a poll using the borrowed waker.
cx.waker().clone().wake(); // Request a poll and consume the owned clone.
A future can call the first form when it chooses to yield even though it has more work it can do. It requests another poll and returns Poll::Pending. The executor must preserve the wake request even though it arrived during the poll. If the executor were to clear the task's runnable flag unconditionally after seeing Pending, it could erase that request and leave the task waiting indefinitely.
Waiting for an external event usually means handing off an owned clone. Imagine a request whose completion producer can run after poll returns. The future checks the request's completion state and, if it needs to wait, arranges for the producer to hold cx.waker().clone(). When the producer completes the request, it publishes the completion state, takes the stored Waker, and calls wake() on it. At the next poll the future checks the completion state again. The completed result comes from that state. A wake can also lead to a poll that still returns Pending, and repeated wakes can be satisfied by a single later poll.
Checking the condition and registering the waker must be coordinated. Suppose the future checks an incomplete request, the producer completes it while no waker is registered, and only then does the future register its waker and return Pending. There may be no second completion to wake it. One way to close that race is to protect the completion state and stored waker with the same lock. The future checks and registers under the lock. The producer records completion and takes the stored waker under that lock, then releases the lock before calling it. If the future is polled again while the request is incomplete, update the registration to use the waker from the latest Context. Linux wait queues illustrate the same ordering requirement for publishing a condition and waking a waiter. Linux kernel Driver Basics
Build a waker for a static task
3 min readcore::task provides Context, Waker, RawWaker, and RawWakerVTable on a no_std target. The safe Waker interface hides how the callback reaches the task. When you build a waker directly from core, you supply that implementation. If the kernel has alloc and uses a suitable Arc-backed task, alloc::task::Wake offers a safe construction path as well. Here we write the raw implementation for an allocator-free task record.
A RawWaker pairs a *const () data pointer with a reference to a static RawWakerVTable. Casting to *const () lets the same interface carry pointers to different concrete types. In this example, every pointer used with TASK_VTABLE points to a Task. That record holds only the atomic flag the executor would inspect to decide whether to poll. RawWaker::new packages the pointer and table. Waker::from_raw is the unsafe conversion that lets any safe caller invoke those callbacks through a Waker.
use core::sync::atomic::{AtomicBool, Ordering};
use core::task::{RawWaker, RawWakerVTable, Waker};
pub struct Task {
pub runnable: AtomicBool,
}
unsafe fn clone_task(data: *const ()) -> RawWaker {
RawWaker::new(data, &TASK_VTABLE)
}
unsafe fn wake_task(data: *const ()) {
// SAFETY: This vtable receives pointers to static Task records.
let task = unsafe { &*data.cast::<Task>() };
task.runnable.store(true, Ordering::Relaxed);
}
unsafe fn wake_task_by_ref(data: *const ()) {
// SAFETY: The pointer follows the same contract as in wake_task.
unsafe { wake_task(data) };
}
unsafe fn drop_task(_: *const ()) {}
static TASK_VTABLE: RawWakerVTable =
RawWakerVTable::new(clone_task, wake_task, wake_task_by_ref, drop_task);
pub fn task_waker(task: &'static Task) -> Waker {
let data = (task as *const Task).cast::<()>();
// SAFETY: The record has static storage and the callbacks share it safely.
unsafe { Waker::from_raw(RawWaker::new(data, &TASK_VTABLE)) }
}
The order of the four callbacks in RawWakerVTable::new matters. Read each callback in terms of what it does to the right to use the wake target:
clonecreates another usable handle. Here both handles can refer to the same static record, so copying the pointer and table is enough.wakeschedules the task and consumes this handle. Here scheduling consists of setting the flag. A static record has no per-handle resource to release afterward.wake_by_refschedules the task while leaving this handle usable. It can delegate to the same function here because the static implementation has no ownership to release.dropreleases the handle's resources without scheduling the task. Here there are no per-handle resources, so the callback does nothing.
The executor would build a context with Context::from_waker(&waker) and pass it to the task's poll. To inspect the waker on a host, you need only a static Task initialised with AtomicBool::new(false). Call task_waker(&TASK), wake it, then inspect TASK.runnable.load(Ordering::Relaxed). Reset the flag between operations to tell which call changed it. On a host this gave the expected result: wake_by_ref set the flag, a consumed clone's wake set it, and drop left it false. The sample flag records a request to poll. It carries no completion result and supplies no ordering for other memory. Relaxed is enough for that isolated flag. A real completion path needs its own synchronization for whatever result the future will read. If the executor can go to sleep, recording a runnable task and notifying the sleeping executor are both scheduling responsibilities.
Keep the wake target alive
3 min readThe memory-safety rule is that every callback must have a valid wake target for as long as it needs to access it. The waker must never outlive the task record it references. In the sample, the safe constructor takes &'static Task. A caller cannot pass it a local record borrowed from a stack frame. Every clone can be used after the Context that supplied it has gone away because the record still exists at the same address. The table also remains available for every callback. In addition, Waker is Send and Sync, so callbacks must tolerate calls from different threads. The shared field here is an AtomicBool, which allows those accesses without a data race.
Consider a faulty constructor that takes &Task and returns the same lifetime-free Waker. A future clones it into a registration, and the function owning the task record returns. The registration still holds a pointer into storage whose lifetime has ended. If the producer calls wake(), the cast and dereference in wake_task access that expired record. The raw pointer preserved the address and discarded the borrow's lifetime information. Safe code was able to trigger undefined behaviour because the constructor promised a valid Waker without ensuring the pointer would remain valid.
With dynamically allocated records, an ownership scheme can keep the wake target allocated even after the future completes. For example, a reference-counted implementation can give each live waker one strong reference. Then clone acquires another strong reference, drop releases one, and wake holds its reference while scheduling and releases it afterward. wake_by_ref leaves the caller's reference in place. The same implementation of wake_task_by_ref from the static example would be wrong if wake_task now released a reference. An implementation using a Waker needs thread-safe reference counting, and if scheduling hands the record to another component for later access, that component also needs a valid way to retain it.
Completing the future and reclaiming the record are separate events. A producer may still hold a waker when the future finishes, or when the executor cancels it. The scheduling path needs to handle a late notification without polling a completed future. An executor that reuses task slots must also stop an old notification from being applied to a new occupant. Static storage solves the address lifetime in this lesson because the example uses a dedicated record. Reusing that address for several logical tasks would introduce a task identity problem even if the record itself stayed allocated.
When reviewing a raw waker, follow a clone all the way from poll to wherever it is stored. Ask which object keeps the record alive, what happens when the producer consumes the clone, and what happens if the clone is dropped because the request was cancelled. Check the borrowed wake separately, since that caller can wake again or drop the same handle later. Each of those paths must preserve both the validity of the pointer and the scheduler's ability to observe the request.
The next lesson, The executor and Pin, takes the runnable request from this lesson and shows how the executor uses it to choose a task to poll, and why polling requires Pin.
Key takeaways
- Context supplies the current task's waker during a poll.
- A wake requests another poll and can occur before the current poll returns.
- A RawWaker pairs a data pointer with a static table of four callbacks.
- Every outstanding waker must keep its wake target valid, and Waker callbacks must be safe to use across threads.
Reflect
- Explain to a colleague, in two sentences: trace a wake request from a future or event producer to the executor.
- Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
- What surprised you when you ran the commands yourself?
On a real board
Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.
References and further reading
Official documentation first. Links checked when the lesson was published.