thread_pool/task.rs
1/// A task that runs on a thread pool
2///
3/// A `ThreadPool` instance is pinned to run only a single type of task,
4/// represented by implementations of `Task`. However, it is sometimes useful to
5/// be able to schedule any arbitrary work to run on a thread pool. This can be
6/// done by using `Box<TaskBox>` as the task type.
7pub trait Task: Send + 'static {
8 /// Run the task
9 fn run(self);
10}
11
12/// A version of `Task` intended to use as a trait object
13pub trait TaskBox: Send + 'static {
14 /// Run the task
15 fn run_box(self: Box<Self>);
16}
17
18impl<F> Task for F
19 where F: FnOnce() + Send + 'static,
20{
21 fn run(self) {
22 (self)()
23 }
24}
25
26impl<T: Sized + Task> TaskBox for T {
27 fn run_box(self: Box<Self>) {
28 (*self).run()
29 }
30}
31
32impl Task for Box<TaskBox> {
33 fn run(self) {
34 self.run_box()
35 }
36}