tinyio_core/runtime/
scheduler.rs

1use std::sync::Arc;
2
3use crate::util::signal::Counter;
4
5use super::{slot::ThreadSlots, task::Task};
6
7#[derive(Debug)]
8pub struct Scheduler {
9    #[allow(unused)]
10    capacity: usize,
11    slots: ThreadSlots,
12    counter: Counter,
13}
14
15impl Scheduler {
16    pub fn new(capacity: usize) -> Self {
17        let slots = ThreadSlots::new(capacity);
18        let counter = Counter::new(0);
19        Self {
20            capacity,
21            slots,
22            counter,
23        }
24    }
25
26    pub fn try_schedule(&mut self, task: Arc<Task>) -> Option<()> {
27        task.mark(&self.counter);
28        let slot = self.slots.allocate();
29        match &slot.worker {
30            Some(worker) => {
31                worker.send(task);
32            }
33            None => {
34                let worker = slot.make_worker(self.counter.clone());
35                worker.send(task);
36            }
37        }
38        Some(())
39    }
40
41    pub fn done(&self) -> bool {
42        self.counter.value() == 0
43    }
44
45    pub fn task_number(&self) -> usize {
46        self.counter.value()
47    }
48}
49
50impl Default for Scheduler {
51    fn default() -> Self {
52        let capacity = num_cpus::get() / 2;
53        Self::new(capacity)
54    }
55}