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
#![cfg_attr(test, recursion_limit = "256")]
#![deny(
clippy::unwrap_used,
missing_docs,
missing_debug_implementations,
missing_copy_implementations,
trivial_casts,
trivial_numeric_casts,
unstable_features,
unused_import_braces,
unused_qualifications
)]
mod config;
mod handler;
mod state;
mod worker;
pub use crate::config::ThreadPoolConfig;
pub use crate::handler::{JoinHandle, ThreadPoolAsyncHandler, ThreadPoolSyncHandler};
use crate::state::State;
use crate::worker::{MsgForWorker, Worker};
use flume::{Receiver as FlumeReceiver, RecvTimeoutError, Sender as FlumeSender};
use std::{
num::NonZeroU16,
sync::{
atomic::{AtomicU32, Ordering},
Arc,
},
time::Duration,
};
#[derive(Clone, Copy, Debug)]
pub struct ThreadPoolDisconnected;
impl std::fmt::Display for ThreadPoolDisconnected {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Thread pool disconnected")
}
}
impl std::error::Error for ThreadPoolDisconnected {}
#[derive(Debug)]
pub struct ThreadPool<Shared: 'static + Clone + Send> {
sender: FlumeSender<MsgForWorker<Shared>>,
}
impl<Shared: 'static + Clone + Send> ThreadPool<Shared> {
pub fn start(config: ThreadPoolConfig, shared: Shared) -> Self {
let state = State::new(config);
let (sender, receiver) = if let Some(queue_size) = config.queue_size {
flume::bounded(queue_size)
} else {
flume::unbounded()
};
for _ in 0..config.min_workers.get() {
let worker = Worker::new(
config.keep_alive,
receiver.clone(),
sender.clone(),
shared.clone(),
state.clone(),
);
std::thread::spawn(move || worker.run());
}
ThreadPool { sender }
}
pub fn async_handler(&self) -> ThreadPoolAsyncHandler<Shared> {
ThreadPoolAsyncHandler::new(self.sender.clone())
}
pub fn sync_handler(&self) -> ThreadPoolSyncHandler<Shared> {
ThreadPoolSyncHandler::new(self.sender.clone())
}
pub fn into_async_handler(self) -> ThreadPoolAsyncHandler<Shared> {
ThreadPoolAsyncHandler::new(self.sender)
}
pub fn into_sync_handler(self) -> ThreadPoolSyncHandler<Shared> {
ThreadPoolSyncHandler::new(self.sender)
}
}
type Job<Shared> = Box<dyn FnOnce(&Shared) + Send + 'static>;
#[cfg(test)]
mod tests {
use super::*;
use std::time::Instant;
const FOUR: NonZeroU16 = unsafe { NonZeroU16::new_unchecked(4) };
#[test]
fn test_sync() -> Result<(), ThreadPoolDisconnected> {
let tp = ThreadPool::start(ThreadPoolConfig::default(), ());
let tp_handler = tp.into_sync_handler();
assert_eq!(4, tp_handler.execute(|_| { 2 + 2 })?);
let start = Instant::now();
let r1 = tp_handler.launch(|_| std::thread::sleep(Duration::from_secs(1)))?;
let r2 = tp_handler.launch(|_| std::thread::sleep(Duration::from_secs(1)))?;
let r3 = tp_handler.launch(|_| std::thread::sleep(Duration::from_secs(1)))?;
let r4 = tp_handler.launch(|_| std::thread::sleep(Duration::from_secs(1)))?;
r1.join().expect("ThreadPool disconnected");
r2.join().expect("ThreadPool disconnected");
r3.join().expect("ThreadPool disconnected");
r4.join().expect("ThreadPool disconnected");
let elapsed = start.elapsed();
assert!(elapsed.as_secs() < 2);
Ok(())
}
#[test]
fn test_async() -> Result<(), ThreadPoolDisconnected> {
futures::executor::block_on(async {
let shared: i32 = 42;
let conf = ThreadPoolConfig::default()
.min_workers(FOUR)
.max_available_workers(FOUR);
println!("conf={:?}", conf);
let tp = ThreadPool::start(conf, shared);
let tp_handler = tp.into_async_handler();
assert_eq!(4u32, tp_handler.execute(|_| { 2 + 2 }).await?);
let start = Instant::now();
use futures::join;
let (res1, res2, res3, res4, res5, res6, res7, res8, res9, res10) = join!(
tp_handler.execute(|_| { std::thread::sleep(Duration::from_secs(1)) }),
tp_handler.execute(|_| { std::thread::sleep(Duration::from_secs(1)) }),
tp_handler.execute(|_| { std::thread::sleep(Duration::from_secs(1)) }),
tp_handler.execute(|_| { std::thread::sleep(Duration::from_secs(1)) }),
tp_handler.execute(|_| { std::thread::sleep(Duration::from_secs(1)) }),
tp_handler.execute(|_| { std::thread::sleep(Duration::from_secs(1)) }),
tp_handler.execute(|_| { std::thread::sleep(Duration::from_secs(1)) }),
tp_handler.execute(|_| { std::thread::sleep(Duration::from_secs(1)) }),
tp_handler.execute(|_| { std::thread::sleep(Duration::from_secs(1)) }),
tp_handler.execute(|_| { std::thread::sleep(Duration::from_secs(1)) }),
);
res1?;
res2?;
res3?;
res4?;
res5?;
res6?;
res7?;
res8?;
res9?;
res10?;
let elapsed = start.elapsed();
assert!(elapsed.as_secs() < 3);
Ok(())
})
}
}