1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
//! This file provides everything to define a [`Executor`] that can execute [`crate::task::Task`].
use ;
use ;
use Result;
/// [`Executor`] can execute [`Task`] concurrently.
///
/// The following example is just to show how [`Task`] and [`Executor`] work.
/// It's not a guarantee that the following code is bug-free.
///
/// # Examples
///
/// ```rust
/// use compiler_base_parallel::task::TaskInfo;
/// use compiler_base_parallel::task::event::TaskEvent;
/// use compiler_base_parallel::task::Task;
/// use compiler_base_parallel::task::TaskStatus;
/// use std::sync::mpsc::Sender;
/// use std::sync::mpsc::channel;
/// use compiler_base_parallel::task::FinishedTask;
/// use compiler_base_parallel::executor::Executor;
/// use compiler_base_parallel::task::event::TaskEventType;
/// use std::thread;
/// use std::io;
/// use anyhow::Result;
///
/// // 1. First, we need to prepare a method to display to the log.
/// // Print the information.
/// fn print_log(event: TaskEvent) -> Result<()> {
/// match event.ty() {
/// TaskEventType::Start => {
/// println!("Task {} start.", event.tinfo())
/// }
/// TaskEventType::Wait => {
/// println!("Task {} waiting.", event.tinfo())
/// }
/// TaskEventType::Timeout(_) => {
/// println!("Task {} timeout.", event.tinfo())
/// }
/// TaskEventType::Finished(ft) => {
/// println!("Task {} finished {}", event.tinfo(), ft)
/// }
/// }
/// Ok(())
/// }
///
/// // 2. Define a custom executor [`MyExec`] for test.
/// pub(crate) struct MyExec {
/// pub(crate) num: usize,
/// }
///
/// // 3. Implement trait [`Executor`] for [`MyExec`].
/// impl Executor for MyExec {
/// fn run_all_tasks<T, F>(self, tasks: &[T], _notify_what_happened: F) -> Result<()>
/// where
/// T: Task + Clone + Sync + Send + 'static,
/// F: Fn(TaskEvent) -> Result<()>,
/// {
/// // The channel for communication.
/// let (tx, rx) = channel::<FinishedTask>();
///
/// // Load all tasks into the thread and execute.
/// let tasks = tasks.to_vec();
/// let mut threads = vec![];
/// let mut t_infos = vec![];
/// for t in tasks {
/// t_infos.push(t.info());
/// let ch = tx.clone();
/// threads.push(thread::spawn(move || t.run(ch)));
/// }
///
/// // Get all the task results and display to the log.
/// for ti in t_infos {
/// let _res = rx.recv().unwrap();
/// _notify_what_happened(TaskEvent::finished(ti, _res))?;
/// }
/// Ok(())
/// }
///
/// fn concurrency_capacity(&self) -> usize {
/// self.num
/// }
/// }
///
/// // 4. Define a custom task [`MyTask`] for test.
/// #[derive(Clone)]
/// struct MyTask {
/// id: usize,
/// name: String,
/// }
///
/// impl MyTask {
/// pub fn new(id: usize, name: String) -> Self {
/// Self { id, name }
/// }
/// }
/// // 5. 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`].
/// ch.send(FinishedTask::new(
/// TaskInfo::new(self.id.into(), self.name.clone().into()),
/// vec![],
/// vec![],
/// TaskStatus::Finished,
/// ))
/// .unwrap();
/// }
///
/// fn info(&self) -> TaskInfo {
/// TaskInfo::new(self.id.into(), self.name.clone().into())
/// }
/// }
///
/// // Create an [`Executor`] with thread count 10.
/// let my_exec = MyExec { num: 10 };
///
/// // Create [`Task`]s
/// let my_tasks = vec![
/// MyTask { id: 0, name:"MyTask0".to_string() },
/// MyTask { id: 1, name:"MyTask1".to_string() },
/// MyTask { id: 2, name:"MyTask2".to_string() },
/// ];
/// my_exec.run_all_tasks(&my_tasks, |x| print_log(x)).unwrap();
/// ```