RustForge

rust-kernel

Rustbelt: a hobby x86_64 kernel written in Rust

rust-kernel / src / task / simple_executor.rs
1221 bytes ยท raw
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
//! The first, naive executor from the chapter: keep a FIFO of tasks and
//! poll them round-robin, over and over, with a waker that does nothing.
//! Works, but busy-polls tasks that can't make progress. Kept for learning
//! (and used in the executor test).

use super::Task;
use alloc::collections::VecDeque;
use core::task::{Context, Poll, Waker};

pub struct SimpleExecutor {
    task_queue: VecDeque<Task>,
}

impl SimpleExecutor {
    pub fn new() -> SimpleExecutor {
        SimpleExecutor { task_queue: VecDeque::new() }
    }

    pub fn spawn(&mut self, task: Task) {
        self.task_queue.push_back(task)
    }

    /// Run until every task has finished.
    pub fn run(&mut self) {
        while let Some(mut task) = self.task_queue.pop_front() {
            let waker = Waker::noop(); // a waker whose wake() does nothing
            let mut context = Context::from_waker(waker);
            match task.poll(&mut context) {
                Poll::Ready(()) => {}                             // done
                Poll::Pending => self.task_queue.push_back(task), // try again later
            }
        }
    }
}

impl Default for SimpleExecutor {
    fn default() -> Self {
        Self::new()
    }
}