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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
use crate::enter;
use crate::unpark_mutex::UnparkMutex;
use futures_core::future::{Future, FutureObj};
use futures_core::task::{Context, Poll, Spawn, SpawnError};
use futures_util::future::FutureExt;
use futures_util::task::{ArcWake, waker_ref};
use std::cmp;
use std::fmt;
use std::io;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::mpsc;
use std::sync::{Arc, Mutex};
use std::thread;
pub struct ThreadPool {
state: Arc<PoolState>,
}
pub struct ThreadPoolBuilder {
pool_size: usize,
stack_size: usize,
name_prefix: Option<String>,
after_start: Option<Arc<dyn Fn(usize) + Send + Sync>>,
before_stop: Option<Arc<dyn Fn(usize) + Send + Sync>>,
}
trait AssertSendSync: Send + Sync {}
impl AssertSendSync for ThreadPool {}
struct PoolState {
tx: Mutex<mpsc::Sender<Message>>,
rx: Mutex<mpsc::Receiver<Message>>,
cnt: AtomicUsize,
size: usize,
}
impl fmt::Debug for ThreadPool {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ThreadPool")
.field("size", &self.state.size)
.finish()
}
}
impl fmt::Debug for ThreadPoolBuilder {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ThreadPoolBuilder")
.field("pool_size", &self.pool_size)
.field("name_prefix", &self.name_prefix)
.finish()
}
}
enum Message {
Run(Task),
Close,
}
impl ThreadPool {
pub fn new() -> Result<ThreadPool, io::Error> {
ThreadPoolBuilder::new().create()
}
pub fn builder() -> ThreadPoolBuilder {
ThreadPoolBuilder::new()
}
pub fn run<F: Future>(&mut self, f: F) -> F::Output {
crate::LocalPool::new().run_until(f)
}
pub fn spawn_obj_ok(&self, future: FutureObj<'static, ()>) {
let task = Task {
future,
wake_handle: Arc::new(WakeHandle {
exec: self.clone(),
mutex: UnparkMutex::new(),
}),
exec: self.clone(),
};
self.state.send(Message::Run(task));
}
pub fn spawn_ok<Fut>(&self, future: Fut)
where
Fut: Future<Output = ()> + Send + 'static,
{
self.spawn_obj_ok(FutureObj::new(Box::new(future)))
}
}
impl Spawn for ThreadPool {
fn spawn_obj(
&mut self,
future: FutureObj<'static, ()>,
) -> Result<(), SpawnError> {
self.spawn_obj_ok(future);
Ok(())
}
}
impl Spawn for &ThreadPool {
fn spawn_obj(
&mut self,
future: FutureObj<'static, ()>,
) -> Result<(), SpawnError> {
self.spawn_obj_ok(future);
Ok(())
}
}
impl PoolState {
fn send(&self, msg: Message) {
self.tx.lock().unwrap().send(msg).unwrap();
}
fn work(&self,
idx: usize,
after_start: Option<Arc<dyn Fn(usize) + Send + Sync>>,
before_stop: Option<Arc<dyn Fn(usize) + Send + Sync>>) {
let _scope = enter().unwrap();
if let Some(after_start) = after_start {
after_start(idx);
}
loop {
let msg = self.rx.lock().unwrap().recv().unwrap();
match msg {
Message::Run(task) => task.run(),
Message::Close => break,
}
}
if let Some(before_stop) = before_stop {
before_stop(idx);
}
}
}
impl Clone for ThreadPool {
fn clone(&self) -> ThreadPool {
self.state.cnt.fetch_add(1, Ordering::Relaxed);
ThreadPool { state: self.state.clone() }
}
}
impl Drop for ThreadPool {
fn drop(&mut self) {
if self.state.cnt.fetch_sub(1, Ordering::Relaxed) == 1 {
for _ in 0..self.state.size {
self.state.send(Message::Close);
}
}
}
}
impl ThreadPoolBuilder {
pub fn new() -> ThreadPoolBuilder {
ThreadPoolBuilder {
pool_size: cmp::max(1, num_cpus::get()),
stack_size: 0,
name_prefix: None,
after_start: None,
before_stop: None,
}
}
pub fn pool_size(&mut self, size: usize) -> &mut Self {
self.pool_size = size;
self
}
pub fn stack_size(&mut self, stack_size: usize) -> &mut Self {
self.stack_size = stack_size;
self
}
pub fn name_prefix<S: Into<String>>(&mut self, name_prefix: S) -> &mut Self {
self.name_prefix = Some(name_prefix.into());
self
}
pub fn after_start<F>(&mut self, f: F) -> &mut Self
where F: Fn(usize) + Send + Sync + 'static
{
self.after_start = Some(Arc::new(f));
self
}
pub fn before_stop<F>(&mut self, f: F) -> &mut Self
where F: Fn(usize) + Send + Sync + 'static
{
self.before_stop = Some(Arc::new(f));
self
}
pub fn create(&mut self) -> Result<ThreadPool, io::Error> {
let (tx, rx) = mpsc::channel();
let pool = ThreadPool {
state: Arc::new(PoolState {
tx: Mutex::new(tx),
rx: Mutex::new(rx),
cnt: AtomicUsize::new(1),
size: self.pool_size,
}),
};
assert!(self.pool_size > 0);
for counter in 0..self.pool_size {
let state = pool.state.clone();
let after_start = self.after_start.clone();
let before_stop = self.before_stop.clone();
let mut thread_builder = thread::Builder::new();
if let Some(ref name_prefix) = self.name_prefix {
thread_builder = thread_builder.name(format!("{}{}", name_prefix, counter));
}
if self.stack_size > 0 {
thread_builder = thread_builder.stack_size(self.stack_size);
}
thread_builder.spawn(move || state.work(counter, after_start, before_stop))?;
}
Ok(pool)
}
}
impl Default for ThreadPoolBuilder {
fn default() -> Self {
Self::new()
}
}
struct Task {
future: FutureObj<'static, ()>,
exec: ThreadPool,
wake_handle: Arc<WakeHandle>,
}
struct WakeHandle {
mutex: UnparkMutex<Task>,
exec: ThreadPool,
}
impl Task {
fn run(self) {
let Task { mut future, wake_handle, mut exec } = self;
let waker = waker_ref(&wake_handle);
let mut cx = Context::from_waker(&waker);
unsafe {
wake_handle.mutex.start_poll();
loop {
let res = future.poll_unpin(&mut cx);
match res {
Poll::Pending => {}
Poll::Ready(()) => return wake_handle.mutex.complete(),
}
let task = Task {
future,
wake_handle: wake_handle.clone(),
exec,
};
match wake_handle.mutex.wait(task) {
Ok(()) => return,
Err(task) => {
future = task.future;
exec = task.exec;
}
}
}
}
}
}
impl fmt::Debug for Task {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Task")
.field("contents", &"...")
.finish()
}
}
impl ArcWake for WakeHandle {
fn wake_by_ref(arc_self: &Arc<Self>) {
match arc_self.mutex.notify() {
Ok(task) => arc_self.exec.state.send(Message::Run(task)),
Err(()) => {}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::mpsc;
#[test]
fn test_drop_after_start() {
let (tx, rx) = mpsc::sync_channel(2);
let _cpu_pool = ThreadPoolBuilder::new()
.pool_size(2)
.after_start(move |_| tx.send(1).unwrap()).create().unwrap();
let count = rx.into_iter().count();
assert_eq!(count, 2);
}
}