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
use std::{
future::Future,
mem,
pin::Pin,
sync::Arc,
thread::{self, JoinHandle},
};
use futures_lite::future;
#[derive(Debug, Default, Clone)]
pub struct TaskPoolBuilder {
num_threads: Option<usize>,
stack_size: Option<usize>,
thread_name: Option<String>,
}
impl TaskPoolBuilder {
pub fn new() -> Self {
Self::default()
}
pub fn num_threads(mut self, num_threads: usize) -> Self {
self.num_threads = Some(num_threads);
self
}
pub fn stack_size(mut self, stack_size: usize) -> Self {
self.stack_size = Some(stack_size);
self
}
pub fn thread_name(mut self, thread_name: String) -> Self {
self.thread_name = Some(thread_name);
self
}
pub fn build(self) -> TaskPool {
TaskPool::new_internal(
self.num_threads,
self.stack_size,
self.thread_name.as_deref(),
)
}
}
struct TaskPoolInner {
threads: Vec<JoinHandle<()>>,
shutdown_tx: async_channel::Sender<()>,
}
impl Drop for TaskPoolInner {
fn drop(&mut self) {
self.shutdown_tx.close();
for join_handle in self.threads.drain(..) {
join_handle
.join()
.expect("task thread panicked while executing");
}
}
}
#[derive(Clone)]
pub struct TaskPool {
executor: Arc<async_executor::Executor>,
inner: Arc<TaskPoolInner>,
}
impl TaskPool {
pub fn new() -> Self {
TaskPoolBuilder::new().build()
}
fn new_internal(
num_threads: Option<usize>,
stack_size: Option<usize>,
thread_name: Option<&str>,
) -> Self {
let (shutdown_tx, shutdown_rx) = async_channel::unbounded::<()>();
let executor = Arc::new(async_executor::Executor::new());
let num_threads = num_threads.unwrap_or_else(num_cpus::get);
let threads = (0..num_threads)
.map(|i| {
let ex = Arc::clone(&executor);
let shutdown_rx = shutdown_rx.clone();
let thread_name = if let Some(thread_name) = thread_name {
format!("{} ({})", thread_name, i)
} else {
format!("TaskPool ({})", i)
};
let mut thread_builder = thread::Builder::new().name(thread_name);
if let Some(stack_size) = stack_size {
thread_builder = thread_builder.stack_size(stack_size);
}
thread_builder
.spawn(move || {
let shutdown_future = ex.run(shutdown_rx.recv());
future::block_on(shutdown_future).unwrap_err();
})
.expect("failed to spawn thread")
})
.collect();
Self {
executor,
inner: Arc::new(TaskPoolInner {
threads,
shutdown_tx,
}),
}
}
pub fn thread_num(&self) -> usize {
self.inner.threads.len()
}
pub fn scope<'scope, F, T>(&self, f: F) -> Vec<T>
where
F: FnOnce(&mut Scope<'scope, T>) + 'scope + Send,
T: Send + 'static,
{
let executor: &async_executor::Executor = &*self.executor;
let executor: &'scope async_executor::Executor = unsafe { mem::transmute(executor) };
let fut = async move {
let mut scope = Scope {
executor,
spawned: Vec::new(),
};
f(&mut scope);
let mut results = Vec::with_capacity(scope.spawned.len());
for task in scope.spawned {
results.push(task.await);
}
results
};
let mut fut = fut;
let fut = unsafe { Pin::new_unchecked(&mut fut) };
let fut: Pin<&mut (dyn Future<Output = Vec<T>> + Send)> = fut;
let fut: Pin<&'static mut (dyn Future<Output = Vec<T>> + Send + 'static)> =
unsafe { mem::transmute(fut) };
future::block_on(self.executor.spawn(fut))
}
pub fn spawn<T>(
&self,
future: impl Future<Output = T> + Send + 'static,
) -> impl Future<Output = T> + Send
where
T: Send + 'static,
{
self.executor.spawn(future)
}
}
impl Default for TaskPool {
fn default() -> Self {
Self::new()
}
}
pub struct Scope<'scope, T> {
executor: &'scope async_executor::Executor,
spawned: Vec<async_executor::Task<T>>,
}
impl<'scope, T: Send + 'static> Scope<'scope, T> {
pub fn spawn<Fut: Future<Output = T> + 'scope + Send>(&mut self, f: Fut) {
let fut: Pin<Box<dyn Future<Output = T> + 'scope + Send>> = Box::pin(f);
let fut: Pin<Box<dyn Future<Output = T> + 'static + Send>> = unsafe { mem::transmute(fut) };
let task = self.executor.spawn(fut);
self.spawned.push(task);
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicI32, Ordering};
#[test]
pub fn test_spawn() {
let pool = TaskPool::new();
let foo = Box::new(42);
let foo = &*foo;
let count = Arc::new(AtomicI32::new(0));
let outputs = pool.scope(|scope| {
for _ in 0..100 {
let count_clone = count.clone();
scope.spawn(async move {
if *foo != 42 {
panic!("not 42!?!?")
} else {
count_clone.fetch_add(1, Ordering::Relaxed);
*foo
}
});
}
});
for output in &outputs {
assert_eq!(*output, 42);
}
assert_eq!(outputs.len(), 100);
assert_eq!(count.load(Ordering::Relaxed), 100);
}
}