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
mod builder;
mod runner;
mod spawn;
mod worker;
pub use self::builder::{Builder, SchedConfig};
pub use self::runner::{CloneRunnerBuilder, Runner, RunnerBuilder};
pub(crate) use self::spawn::WeakRemote;
pub use self::spawn::{build_spawn, Local, Remote};
use crate::queue::{TaskCell, WithExtras};
use std::mem;
use std::sync::Mutex;
use std::thread::{self, JoinHandle};
pub struct ThreadPool<T: TaskCell + Send> {
remote: Remote<T>,
threads: Mutex<Vec<JoinHandle<()>>>,
}
impl<T: TaskCell + Send> ThreadPool<T> {
pub fn spawn(&self, t: impl WithExtras<T>) {
self.remote.spawn(t);
}
pub fn shutdown(&self) {
self.remote.stop();
let mut threads = mem::replace(&mut *self.threads.lock().unwrap(), Vec::new());
let curr_id = thread::current().id();
for j in threads.drain(..) {
if curr_id != j.thread().id() {
j.join().unwrap();
}
}
}
pub fn remote(&self) -> &Remote<T> {
&self.remote
}
}
impl<T: TaskCell + Send> Drop for ThreadPool<T> {
fn drop(&mut self) {
self.shutdown();
}
}
#[cfg(test)]
mod tests;