twizzler_async/
exec.rs

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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
use std::{collections::VecDeque, future::Future, sync::Mutex};

use scoped_tls_hkt::scoped_thread_local;

use crate::{
    event::FlagEvent,
    task::{Runnable, Task},
    throttle,
};

scoped_thread_local! {
    static WORKER: for<'a> &'a Worker<'a>
}

pub(crate) struct Executor {
    avail: FlagEvent,
    queue: Mutex<VecDeque<Runnable>>,
}

lazy_static::lazy_static! {
    static ref EXECUTOR: Executor = {
        Executor {
            avail: FlagEvent::new(),
            queue: Mutex::new(VecDeque::new()),
        }
    };
}

impl Executor {
    pub fn get() -> &'static Self {
        &EXECUTOR
    }

    pub fn notify_work(&self) {
        self.event().notify();
    }

    pub fn event(&self) -> &FlagEvent {
        &self.avail
    }

    pub fn spawn<T: Send + 'static>(
        &'static self,
        future: impl Future<Output = T> + Send + 'static,
    ) -> Task<T> {
        let schedule = move |runnable: async_task::Task<u32>| {
            {
                let mut queue = self.queue.lock().unwrap();
                queue.push_front(runnable);
                drop(queue);
            }
            self.notify_work();
        };
        let (runnable, handle) = async_task::spawn(future, schedule, 45678);
        runnable.schedule();
        Task(Some(handle))
    }

    pub fn worker(&self) -> Worker<'_> {
        Worker {
            // current: Cell::new(None),
            exec: self,
        }
    }
}

pub(crate) struct Worker<'a> {
    //current: Cell<Option<Runnable>>,
    exec: &'a Executor,
}

impl Worker<'_> {
    pub fn enter<T>(&self, f: impl FnOnce() -> T) -> T {
        if WORKER.is_set() {
            panic!("cannot run an executor recursively");
        }
        WORKER.set(self, f)
    }

    pub fn execute(&self) -> bool {
        for _ in 0..4 {
            for _ in 0..50 {
                match self.search() {
                    None => {
                        return false;
                    }
                    Some(r) => {
                        // TODO: why?
                        self.exec.notify_work();

                        if throttle::setup(|| r.run()) {}
                    }
                }
            }
        }
        true
    }

    #[allow(named_asm_labels)]
    fn search(&self) -> Option<Runnable> {
        let mut queue = self.exec.queue.lock().unwrap();
        queue.pop_front()
    }
}

impl Drop for Worker<'_> {
    fn drop(&mut self) {
        self.exec.notify_work();
    }
}