task_deque.rs 2.5 KB

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