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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
extern crate libc;
use std::panic;
use std::panic::AssertUnwindSafe;
use std::sync::mpsc::{channel, Sender, Receiver, SyncSender, sync_channel, RecvError};
use std::sync::{Arc, Mutex};
use std::thread::{self, JoinHandle};
mod mutex;
pub use mutex::{ReentrantMutex, ReentrantMutexGuard};
trait FnBox {
fn call_box(self: Box<Self>);
}
impl<F: FnOnce()> FnBox for F {
fn call_box(self: Box<F>) {
(*self)()
}
}
type Thunk<'a> = Box<FnBox + Send + 'a>;
enum Message {
NewJob(Thunk<'static>),
Join,
}
pub struct ThreadPool {
threads: Vec<ThreadData>,
job_sender: Sender<Message>,
job_receiver: Arc<Mutex<Receiver<Message>>>,
active_count: Arc<Mutex<usize>>,
max_count: Arc<Mutex<usize>>,
name: String,
}
struct ThreadData {
_thread_join_handle: JoinHandle<()>,
pool_sync_rx: Receiver<()>,
thread_sync_tx: SyncSender<()>,
}
fn create_thread(job_receiver: Arc<Mutex<Receiver<Message>>>,
active_count: Arc<Mutex<usize>>,
name: String)
-> ThreadData {
let job_receiver = job_receiver.clone();
let (pool_sync_tx, pool_sync_rx) = sync_channel::<()>(0);
let (thread_sync_tx, thread_sync_rx) = sync_channel::<()>(0);
let thread = thread::Builder::new()
.name(name)
.spawn(move || {
loop {
let result = panic::catch_unwind(AssertUnwindSafe(|| {
let message = {
let lock = job_receiver.lock().unwrap();
lock.recv()
};
match message {
Ok(Message::NewJob(job)) => {
*active_count.lock().unwrap() += 1;
job.call_box();
*active_count.lock().unwrap() -= 1;
}
Ok(Message::Join) => {
if pool_sync_tx.send(()).is_err() {
return;
}
if thread_sync_rx.recv().is_err() {
return;
}
}
Err(..) => {
return;
}
}
}));
if result.is_err() {
println!("thread error is {:?}", result);
}
}
})
.ok()
.unwrap();
ThreadData {
_thread_join_handle: thread,
pool_sync_rx: pool_sync_rx,
thread_sync_tx: thread_sync_tx,
}
}
impl ThreadPool {
pub fn new(n: usize) -> ThreadPool {
Self::new_with_name(n, "unknow".to_string())
}
pub fn new_with_name(n: usize, name: String) -> ThreadPool {
assert!(n >= 1);
let (job_sender, job_receiver) = channel();
let job_receiver = Arc::new(Mutex::new(job_receiver));
let active_count = Arc::new(Mutex::new(0));
let max_count = Arc::new(Mutex::new(n as usize));
let mut threads = Vec::with_capacity(n as usize);
for _ in 0..n {
let thread = create_thread(job_receiver.clone(), active_count.clone(), name.clone());
threads.push(thread);
}
ThreadPool {
threads: threads,
job_sender: job_sender,
job_receiver: job_receiver.clone(),
active_count: active_count,
max_count: max_count,
name: name,
}
}
pub fn thread_count(&self) -> usize {
self.threads.len()
}
pub fn execute<F>(&self, job: F)
where F: FnOnce() + Send + 'static
{
self.job_sender.send(Message::NewJob(Box::new(job))).unwrap();
}
pub fn join_all(&self) {
for _ in 0..self.threads.len() {
self.job_sender.send(Message::Join).unwrap();
}
let mut worker_panic = false;
for thread_data in &self.threads {
if let Err(RecvError) = thread_data.pool_sync_rx.recv() {
worker_panic = true;
}
}
if worker_panic {
panic!("Thread pool worker panicked");
}
for thread_data in &self.threads {
thread_data.thread_sync_tx.send(()).unwrap();
}
}
pub fn active_count(&self) -> usize {
*self.active_count.lock().unwrap()
}
pub fn max_count(&self) -> usize {
*self.max_count.lock().unwrap()
}
pub fn set_threads(&mut self, threads: usize) -> i32 {
assert!(threads >= 1);
if threads <= self.thread_count() {
return -1;
}
for _ in 0..(threads - self.thread_count()) {
let thread = create_thread(self.job_receiver.clone(),
self.active_count.clone(),
self.name.clone());
self.threads.push(thread);
}
*self.max_count.lock().unwrap() = threads;
0
}
}