-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththreadpool.rs
More file actions
101 lines (85 loc) · 2.37 KB
/
Copy paththreadpool.rs
File metadata and controls
101 lines (85 loc) · 2.37 KB
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
use std::error::Error;
use std::sync::{Arc, Mutex, mpsc, mpsc::Receiver};
use std::thread;
use std::thread::JoinHandle;
pub struct Worker {
id: usize,
thread: Option<JoinHandle<()>>,
}
type ReceiverEnd = Arc<Mutex<Receiver<Job>>>;
impl Worker {
pub fn new(id: usize, rx: ReceiverEnd) -> Self {
let thread = thread::spawn(move || {
loop {
let job = {
let rx = rx.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
rx.recv()
};
match job {
Ok(job) => job(),
Err(_) => {
eprintln!("Worker {} shutting down.", id);
break;
}
}
}
});
Worker {
id,
thread: Some(thread),
}
}
}
type Job = Box<dyn FnOnce() + Send + 'static>;
pub struct ThreadPool {
workers: Vec<Worker>,
tx: Option<mpsc::Sender<Job>>,
}
impl ThreadPool {
fn new(size: usize) -> Self {
let (tx, rx) = mpsc::channel();
let rx = Arc::new(Mutex::new(rx));
let mut workers = Vec::with_capacity(size);
for id in 0..size {
workers.push(Worker::new(id, Arc::clone(&rx)));
}
ThreadPool {
workers,
tx: Some(tx),
}
}
pub fn build(size: usize) -> Result<Self, Box<dyn Error>> {
if size > 0 {
Ok(ThreadPool::new(size))
} else {
Err(Box::new(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
"size must be greater than 0",
)))
}
}
pub fn execute<F>(&self, f: F) -> Result<(), Box<dyn Error>>
where
F: FnOnce() + Send + 'static,
{
let job = Box::new(f);
self.tx
.as_ref()
.ok_or("thread pool has been shut down")?
.send(job)
.map_err(|e| e.into())
}
}
impl Drop for ThreadPool {
fn drop(&mut self) {
drop(self.tx.take());
for worker in &mut self.workers {
println!("Shutting down worker {}", worker.id);
if let Some(thread) = worker.thread.take() {
if thread.join().is_err() {
eprintln!("worker {} panicked.", worker.id);
}
}
}
}
}