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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
#![feature(fnbox)]
use std::boxed::FnBox;
#[macro_use]
extern crate stderr;
extern crate num_cpus;
use std::sync::{Arc, Mutex, RwLock, Condvar};
use std::sync::atomic::{Ordering, AtomicUsize};
use std::collections::VecDeque;
use std::time::Duration;
use std::error::Error;
use std::thread;
const TIME_OUT_MS: u64 = 5_000;
pub struct Pool {
water: Arc<Water>,
name: Option<String>,
stack_size: Option<usize>,
load_limit: usize,
}
struct Water {
tasks: Mutex<VecDeque<Box<FnBox() + Send + 'static>>>,
condvar: Condvar,
threads: AtomicUsize,
threads_waited: AtomicUsize,
min_timeout: RwLock<(usize, u64)>,
}
impl Pool {
pub fn new() -> Pool {
let cpus_num = num_cpus::get();
Pool {
water: Arc::new(Water {
tasks: Mutex::new(VecDeque::new()),
condvar: Condvar::new(),
threads: AtomicUsize::new(0),
threads_waited: AtomicUsize::new(0),
min_timeout: RwLock::new((cpus_num + 1, TIME_OUT_MS)),
}),
name: None,
stack_size: None,
load_limit: cpus_num,
}
}
pub fn min(self, min: usize) -> Pool {
{
let mut rw_min_timeout = match self.water.min_timeout.write() {
Ok(ok) => ok,
Err(e) => e.into_inner(),
};
let (.., timeout) = *rw_min_timeout;
*rw_min_timeout = (min, timeout);
}
self
}
pub fn time_out(self, time_out: u64) -> Pool {
{
let mut rw_min_timeout = match self.water.min_timeout.write() {
Ok(ok) => ok,
Err(e) => e.into_inner(),
};
let (min, ..) = *rw_min_timeout;
*rw_min_timeout = (min, time_out);
}
self
}
pub fn name<T: AsRef<str>>(mut self, name: T) -> Pool {
self.name = Some(name.as_ref().to_string());
self
}
pub fn stack_size(mut self, size: usize) -> Pool {
self.stack_size = Some(size);
self
}
pub fn load_limit(mut self, load_limit: usize) -> Pool {
self.load_limit = load_limit;
self
}
pub fn run(self) -> Pool {
let ro_min = match self.water.min_timeout.read() {
Ok(ok) => ok.0,
Err(e) => e.into_inner().0,
};
for _ in 0..ro_min {
self.add_thread();
}
self
}
pub fn is_empty(&self) -> bool {
self.wait_len() == self.len() && self.tasks_len() == 0
}
#[inline]
pub fn tasks_len(&self) -> usize {
match self.water.tasks.lock() {
Ok(ok) => ok.len(),
Err(e) => e.into_inner().len(),
}
}
#[inline]
pub fn strong_count(&self) -> usize {
Arc::strong_count(&self.water)
}
#[inline]
pub fn len(&self) -> usize {
(&self.water.threads).load(Ordering::Acquire)
}
#[inline]
pub fn wait_len(&self) -> usize {
(&self.water.threads_waited).load(Ordering::Acquire)
}
pub fn spawn(&self, task: Box<FnBox() + Send + 'static>) {
let tasks_queue_len = {
let mut tasks_queue = match self.water.tasks.lock() {
Ok(ok) => ok,
Err(e) => e.into_inner(),
};
tasks_queue.push_back(task);
tasks_queue.len()
};
if self.wait_len() == 0 && tasks_queue_len / self.strong_count() > self.load_limit + 1 {
self.add_thread();
} else {
self.water.condvar.notify_one();
}
}
fn add_thread(&self) {
let water = self.water.clone();
let mut thread = match self.name.clone() {
Some(name) => thread::Builder::new().name(name),
None => thread::Builder::new(),
};
thread = match self.stack_size {
Some(size) => thread.stack_size(size),
None => thread,
};
let spawn_res = thread
.spawn(move || {
let water = water;
let _threads_counter = Counter::add(&water.threads);
loop {
let task;
{
let mut tasks_queue = match water.tasks.lock() {
Ok(ok) => ok,
Err(e) => e.into_inner(),
};
loop {
if let Some(poped_task) = tasks_queue.pop_front() {
task = poped_task;
break;
}
let _threads_waited_counter = Counter::add(&water.threads_waited);
let (ro_min,ro_time_out) = match water.min_timeout.read() {
Ok(ok) => *ok,
Err(e) => *e.into_inner(),
};
let (new_tasks_queue, waitres) =match water.condvar
.wait_timeout(tasks_queue, Duration::from_millis(ro_time_out)) {
Ok(ok)=>ok,
Err(e)=>e.into_inner(),
};
tasks_queue=new_tasks_queue;
if waitres.timed_out() && tasks_queue.is_empty() && (&water.threads).load(Ordering::Acquire) >ro_min {
return;
}
}
}
task();
}
});
match spawn_res {
Ok(..) => {}
Err(e) => {
errstln!("Poolite_Warnig: create new thread failed because of '{}' !",
e.description())
}
};
}
}
impl Drop for Pool {
fn drop(&mut self) {
self.water.threads.store(usize::max_value(), Ordering::Release);
self.water.condvar.notify_all();
}
}
struct Counter<'a> {
count: &'a AtomicUsize,
}
impl<'a> Counter<'a> {
fn add(count: &'a AtomicUsize) -> Counter<'a> {
count.fetch_add(1, Ordering::Release);
Counter { count: count }
}
}
impl<'a> Drop for Counter<'a> {
fn drop(&mut self) {
self.count.fetch_sub(1, Ordering::Release);
}
}