pub trait Task {
// Required methods
fn run(&self, ch: Sender<FinishedTask>);
fn info(&self) -> TaskInfo;
}
Expand description
Task
is the unit that crate::executor::Executor
can execute concurrently.
§Example
use compiler_base_parallel::task::Task;
use compiler_base_parallel::task::FinishedTask;
use std::sync::mpsc::channel;
use std::sync::mpsc::Sender;
use compiler_base_parallel::task::TaskName;
use compiler_base_parallel::task::TaskId;
use compiler_base_parallel::task::TaskInfo;
use compiler_base_parallel::task::TaskStatus;
// 1. Define a custom task [`MyTask`].
struct MyTask {
id: usize,
name: String,
}
// 2. Implement trait [`Task`] for [`MyTask`].
impl Task for MyTask {
fn run(&self, ch: Sender<FinishedTask>) {
// [`FinishedTask`] is constructed here passed to other threads via [`ch`].
let res = FinishedTask::new(self.info(), vec![], vec![], TaskStatus::Finished);
ch.send(res).unwrap();
}
fn info(&self) -> TaskInfo {
TaskInfo::new(self.id.into(), self.name.to_string().into())
}
}
impl MyTask {
pub fn new(id: usize, name: String) -> Self {
Self { id, name }
}
}
// 3. Create [`channel`] to pass [`FinishedTask`].
let (tx, rx) = channel::<FinishedTask>();
let my_task = MyTask::new(0, "MyTask 0".to_string());
my_task.run(tx);
// 4. [`FinishedTask`] created in [`Task`] will be got from channel.
match rx.recv() {
Ok(res) => {
assert_eq!(res.tinfo().tid(), 0.into());
assert_eq!(res.tinfo().tname(), "MyTask 0".to_string().into());
assert_eq!(res.status(), TaskStatus::Finished);
},
Err(_) => panic!("unreachable code")
}
Required Methods§
Sourcefn run(&self, ch: Sender<FinishedTask>)
fn run(&self, ch: Sender<FinishedTask>)
[run
] will be executed of the Task
,
and the result of the execution is communicated with other threads through the [ch
] which is a Sender<FinishedTask>
,
so [run
] method does not need to return a value.
Note: If the [run
] method panics before returning the result through the [ch
],
nothing will be output, and the outside world will not be able to get the running status of the task.
Therefore, when implementing the [run
] method,
please try to handle the failure case as much as possible to ensure that all result can be sent to [ch
].
If you can not get the results properly and you are confident that all the possible results are returned through [ch
],
please contact us, this maybe a bug.