Skip to main content

os/task/
simple_executor.rs

1use super::Task;
2use alloc::collections::VecDeque;
3
4pub struct SimpleExecutor {
5    task_queue: VecDeque<Task>,
6}
7
8impl SimpleExecutor {
9    pub fn new() -> Self {
10        Self {
11            task_queue: VecDeque::new(),
12        }
13    }
14
15    pub fn spawn(&mut self, task: Task) {
16        self.task_queue.push_back(task)
17    }
18}
19
20impl Default for SimpleExecutor {
21    fn default() -> Self {
22        Self::new()
23    }
24}
25
26use core::task::{RawWaker, Waker};
27
28fn dummy_raw_waker() -> RawWaker {
29    fn no_op(_: *const ()) {}
30    fn clone(_: *const ()) -> RawWaker {
31        dummy_raw_waker()
32    }
33
34    let vtable = &RawWakerVTable::new(clone, no_op, no_op, no_op);
35    RawWaker::new(core::ptr::null::<()>(), vtable)
36}
37
38fn dummy_waker() -> Waker {
39    unsafe { Waker::from_raw(dummy_raw_waker()) }
40}
41use core::task::RawWakerVTable;
42
43use core::task::{Context, Poll};
44
45impl SimpleExecutor {
46    pub fn run(&mut self) {
47        while let Some(mut task) = self.task_queue.pop_front() {
48            let waker = dummy_waker();
49            let mut context = Context::from_waker(&waker);
50            match task.poll(&mut context) {
51                Poll::Ready(()) => {} // 任务完成
52                Poll::Pending => self.task_queue.push_back(task),
53            }
54        }
55    }
56}