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
use crossbeam_channel::{Receiver, Sender, unbounded};
use num_cpus;
use log::{error, info};
use std::{sync::{Arc, RwLock}, thread::JoinHandle, time::{Instant, Duration}};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ExecutorError{
CouldNotSendTask
}
pub const TASK_FETCHING_TIMEOUT: u64 = 100;
struct Thread{
id: usize,
handle: Option<JoinHandle<()>>,
stop_sig: Arc<RwLock<bool>>,
}
impl Thread{
fn new(id: usize, task_receiver: Receiver<Task>) -> Self{
let stop_sig = Arc::new(RwLock::new(false));
let stpsig = stop_sig.clone();
let handle = std::thread::spawn(move ||{
while !*stpsig.read().unwrap(){
if let Ok(t) = task_receiver.recv_timeout(Duration::from_millis(TASK_FETCHING_TIMEOUT)){
info!("Exec task in [{}]", id);
t.execute();
}
}
info!("Exit thread[{}]", id);
});
Thread{
id,
handle: Some(handle),
stop_sig
}
}
}
impl Drop for Thread{
fn drop(&mut self){
info!("Dropping thread[{}]", self.id);
*self.stop_sig.write().unwrap() = true;
if let Some(hdl) = self.handle.take(){
if let Err(e) = hdl.join(){
error!("Failed to join worker thread[{}], might be dangling now! Err: {:?}", self.id, e);
}
}
}
}
pub struct Executor{
#[allow(dead_code)]
threads: Vec<Thread>,
task_sender: Sender<Task>,
task_receiver: Receiver<Task>,
}
impl Executor{
pub fn new() -> Arc<Self>{
let (task_sender, task_receiver) = unbounded();
let threads: Vec<_> = (0..num_cpus::get()).into_iter().map(|i| Thread::new(i, task_receiver.clone())).collect();
info!("Created {} threads for executor", threads.len());
Arc::new(Executor{
task_sender,
threads,
task_receiver
})
}
pub fn new_with_threads(num_threads: usize) -> Arc<Self>{
let (task_sender, task_receiver) = unbounded();
let threads: Vec<_> = (0..num_threads).into_iter().map(|i| Thread::new(i, task_receiver.clone())).collect();
info!("Created {} threads for executor based on input", threads.len());
Arc::new(Executor{
task_sender,
threads,
task_receiver
})
}
pub fn schedule(&self, new_task: Task) -> Result<(), ExecutorError>{
if let Err(e) = self.task_sender.try_send(new_task){
error!("Failed to schedule task: Could not send: {}", e);
Err(ExecutorError::CouldNotSendTask)
}else{
Ok(())
}
}
pub fn shutdown(&self){
while self.task_receiver.len() > 0{
std::thread::sleep(Duration::from_millis(TASK_FETCHING_TIMEOUT));
}
}
}
pub struct Task{
task: Box<dyn FnOnce() + Send>
}
impl Task{
pub fn new<T>(task: T) -> Self where T: FnOnce() + Send + 'static{
Task{
task: Box::new(task)
}
}
pub fn execute(self){
(self.task)()
}
}
#[allow(dead_code)]
fn sec_task(secs: u64) -> Task{
Task::new(move || {
let start = Instant::now();
while start.elapsed() < Duration::from_secs(secs){
std::thread::sleep(Duration::from_millis(100));
}
})
}
#[test]
fn test_executor(){
let ex = Executor::new();
let _t1 = sec_task(1);
let _t2 = sec_task(2);
let _t3 = sec_task(3);
let _t4 = sec_task(1);
ex.shutdown();
}