xref: /DADK/dadk-user/src/scheduler/task_deque.rs (revision c9f71754563759e653d59a110f15298891564be9)
1 use std::{
2     path::PathBuf,
3     sync::{Arc, Mutex},
4     thread::JoinHandle,
5 };
6 
7 use crate::{context::Action, scheduler::TID_EID};
8 
9 use super::{SchedEntity, Scheduler};
10 
11 // 最大线程数
12 pub const MAX_THREAD_NUM: usize = 32;
13 // 默认线程数
14 pub const DEFAULT_THREAD_NUM: usize = 2;
15 
16 lazy_static! {
17     // 全局任务队列
18     pub static ref TASK_DEQUE: Mutex<TaskDeque> = Mutex::new(TaskDeque {
19         max_num: DEFAULT_THREAD_NUM,
20         queue: Vec::new(),
21     });
22 }
23 
24 /// # 任务队列
25 pub struct TaskDeque {
26     max_num: usize,
27     queue: Vec<JoinHandle<()>>,
28 }
29 
30 impl TaskDeque {
31     /// 将构建或安装DADK任务添加到任务队列中
32     ///
33     /// ## 参数
34     ///
35     /// - `action` : 要执行的操作
36     /// - `dragonos_dir` : DragonOS sysroot在主机上的路径
37     /// - `entity` : 任务实体
38     ///
39     /// ## 返回值
40     ///
41     /// true 任务添加成功
42     /// false 任务添加失败
43     pub fn build_install_task(
44         &mut self,
45         action: Action,
46         dragonos_dir: PathBuf,
47         entity: Arc<SchedEntity>,
48     ) -> bool {
49         // log::warn!("push stack: task:{} {entity:?}", entity.id());
50         if self.queue.len() < self.max_num {
51             let id = entity.id();
52             let handler = std::thread::spawn(move || {
53                 Scheduler::execute(action, dragonos_dir.clone(), entity)
54             });
55             TID_EID.lock().unwrap().insert(handler.thread().id(), id);
56             self.queue.push(handler);
57             return true;
58         }
59         return false;
60     }
61 
62     /// 将清理DADK任务添加到任务队列中
63     ///
64     /// ## 参数
65     ///
66     /// - `action` : 要执行的操作
67     /// - `dragonos_dir` : DragonOS sysroot在主机上的路径
68     /// - `entity` : 任务实体
69     ///
70     /// ## 返回值
71     ///
72     /// 无
73     pub fn clean_task(&mut self, action: Action, dragonos_dir: PathBuf, entity: Arc<SchedEntity>) {
74         while self.queue.len() >= self.max_num {
75             self.queue.retain(|x| !x.is_finished());
76         }
77         let handler =
78             std::thread::spawn(move || Scheduler::execute(action, dragonos_dir.clone(), entity));
79         self.queue.push(handler);
80     }
81 
82     pub fn queue(&self) -> &Vec<JoinHandle<()>> {
83         return &self.queue;
84     }
85 
86     pub fn queue_mut(&mut self) -> &mut Vec<JoinHandle<()>> {
87         return &mut self.queue;
88     }
89 
90     pub fn set_thread(&mut self, mut thread: usize) {
91         if thread > MAX_THREAD_NUM {
92             thread = MAX_THREAD_NUM;
93         }
94         self.max_num = thread;
95     }
96 }
97