2 个版本
0.1.1 | 2021年7月24日 |
---|---|
0.1.0 | 2021年7月24日 |
#1121 在 并发
19KB
421 行
任务队列
描述
支持在运行中的任务中添加新任务的并行执行任务队列
示例
let thread_count = 2;
let queue_type = QueueType::Stack;
let task_queue = TaskQueue::new(thread_count, queue_type);
其中 thread_count
- 并行执行任务的线程数量 queue_type
- 确定任务将在队列的开始或结束时添加(可用值:队列,栈)
struct RecursiveTimeoutTask {
timeout_sec: u64,
deep: u8,
}
impl RecursiveTimeoutTask {
fn new(timeout_sec: u64, deep: u8) -> Self {
Self { timeout_sec, deep }
}
}
impl RunTask for RecursiveTimeoutTask {
fn run(self: Box<Self>, _id: WorkerId, task_receiver: TaskReceiver) -> TaskControlCommand {
std::thread::sleep(std::time::Duration::from_secs(self.timeout_sec));
if self.deep > 0 {
task_receiver.add_task(Box::new(RecursiveTimeoutTask::new(
self.timeout_sec,
self.deep - 1,
)));
}
TaskControlCommand::Continue
}
}
要将任务添加到队列中,您需要实现 RunTask
特性。第三个参数 task_receiver
用于添加新任务。方法 run
返回 TaskControlCommand
,可用值 Continue
- 默认值,不会以任何方式影响队列的操作,Abort
- 重置待处理的任务,不接收新的任务,任务队列将不再执行外部添加的任务。
// Add new task
task_queue.add_task(Box::new(RecursiveTimeoutTask::new(2, 4)))?;
task_queue.add_task(Box::new(RecursiveTimeoutTask::new(5, 2)))?;
// Cancel tasks and wait for the completion of task processing (Analogue - TaskControlCommand::Abort)
task_queue.abort()?;
// Wait untill all tasks are completed
task_queue.join()?;
! 如果不使用 abort
/ join
,则将使用丢弃,但不会处理工作进程的恐慌,请使用 join。
依赖关系
~1.5MB
~36K SLoC