RawWakerVTable functions, did I write them correctly?

⚓ Rust    📅 2026-04-14    👤 surdeus    👁️ 4      

surdeus

Hi folks, I am trying to understand how tokio does what it does by writing a small executor of mine. I am at a point where am writing a VTable for constructing a Waker. I have written all the 4 functions which are required to construct a RawWakerVTable. Please let me know if they look okay to you..thanks!

also, std::mem::forget(task) is the correct thing to do cause we are only given a pointer and we do not own an Arc<Task> therefore we shouldn't drop it, correct?

// RawWakerVTable functions
// for each operation on the Waker, the associated function in the vtable will be called.
mod vtable {
    use crate::*;
    pub fn clone(data: *const ()) -> RawWaker {
        RawWaker::new(data, &Executor::VTABLE)
    }

    pub fn wake(data: *const ()) {
        let task: Arc<Task> = unsafe { Arc::from_raw(data as _) };
        // schedule the task on the executor again
        task.send(task.clone());
        // we don't own `data` so we don't drop it?
        std::mem::forget(task);
    }

    // I don't know how this would differ from wake...
    pub fn wake_by_ref(data: *const ()) {
        let task: Arc<Task> = unsafe { Arc::from_raw(data as _) };
        // schedule the task on the executor again
        task.send(task.clone());
        // we don't own `data` so we don't drop it?
        std::mem::forget(task);
    }

    pub fn drop(data: *const ()) {
        unsafe { Arc::<Task>::from_raw(data as _) };
    }
}
   const VTABLE: RawWakerVTable = RawWakerVTable::new(
        vtable::clone,
        vtable::wake,
        vtable::wake_by_ref,
        vtable::drop,
    );

at its core the main purpose of writing all of this is to schedule the task back to the executor so we could call poll on it again, correct?

Ik, I could have also implemented ArcWake but, I wanted know what is actually happening under the hood so I just did it this way :slight_smile:

3 posts - 3 participants

Read full topic

🏷️ Rust_feed