1use std::sync::Arc;
3use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering, fence};
4use std::task::{Context, Poll};
5use std::time::{Duration, Instant};
6use std::{any::Any, fmt, future::Future, panic, pin::Pin, thread};
7
8use crossbeam_channel::{Receiver, Select, Sender, TrySendError, bounded, unbounded};
9
10pub fn spawn_blocking<F, R>(f: F) -> BlockingResult<R>
22where
23 F: FnOnce() -> R + Send + 'static,
24 R: Send + 'static,
25{
26 crate::System::with_current(|sys| match sys {
27 Some(sys) => sys.spawn_blocking(f),
28 None => ThreadPool::execute_inplace(f),
29 })
30}
31
32#[derive(Copy, Clone, Debug, PartialEq, Eq)]
37pub struct BlockingError;
38
39impl std::error::Error for BlockingError {}
40
41impl fmt::Display for BlockingError {
42 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
43 "Blocking task failed or was canceled".fmt(f)
44 }
45}
46
47#[derive(Debug)]
54pub struct BlockingResult<T> {
55 rx: oneshot::AsyncReceiver<Result<T, Box<dyn Any + Send>>>,
56 detached: Option<Arc<AtomicBool>>,
57}
58
59impl<T> BlockingResult<T> {
60 pub fn detach(self) {
64 if let Some(detached) = &self.detached {
65 detached.store(true, Ordering::Relaxed);
67 }
68 }
69}
70
71#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
82#[non_exhaustive]
83pub struct PoolMetrics {
84 pub thread_limit: usize,
86 pub threads: usize,
88 pub active_tasks: usize,
90 pub queue_depth: usize,
92 pub max_queue_depth: usize,
94 pub saturated_tasks: u64,
98 pub tasks: u64,
100 pub wait_duration: Duration,
102 pub busy_duration: Duration,
104}
105
106impl PoolMetrics {
107 pub(crate) fn add_totals(&mut self, other: &PoolMetrics) {
109 self.max_queue_depth = self.max_queue_depth.max(other.max_queue_depth);
110 self.saturated_tasks = self.saturated_tasks.saturating_add(other.saturated_tasks);
111 self.tasks = self.tasks.saturating_add(other.tasks);
112 self.wait_duration = self.wait_duration.saturating_add(other.wait_duration);
113 self.busy_duration = self.busy_duration.saturating_add(other.busy_duration);
114 }
115
116 pub(crate) fn add(&mut self, other: &PoolMetrics) {
118 self.thread_limit = self.thread_limit.saturating_add(other.thread_limit);
119 self.threads += other.threads;
120 self.active_tasks += other.active_tasks;
121 self.queue_depth += other.queue_depth;
122 self.add_totals(other);
123 }
124}
125
126#[derive(Debug, Default)]
127struct PoolStats {
128 active: AtomicUsize,
129 max_queue: AtomicUsize,
130 saturated: AtomicU64,
131 tasks: AtomicU64,
132 wait: AtomicU64,
134 busy: AtomicU64,
135}
136
137fn as_nanos(d: Duration) -> u64 {
138 u64::try_from(d.as_nanos()).unwrap_or(u64::MAX)
139}
140
141type BoxedDispatchable = Box<dyn Dispatchable + Send>;
142
143pub(crate) trait Dispatchable: Send + 'static {
144 fn run(self: Box<Self>);
145}
146
147impl<F> Dispatchable for F
148where
149 F: FnOnce() + Send + 'static,
150{
151 fn run(self: Box<Self>) {
152 (*self)();
153 }
154}
155
156struct CounterGuard(Arc<AtomicUsize>);
158
159impl CounterGuard {
160 fn reserve(counter: &Arc<AtomicUsize>, limit: usize) -> Option<(Self, usize)> {
161 counter
162 .try_update(Ordering::AcqRel, Ordering::Acquire, |cnt| {
163 (cnt < limit).then_some(cnt + 1)
164 })
165 .ok()
166 .map(|cnt| (CounterGuard(counter.clone()), cnt))
167 }
168}
169
170impl Drop for CounterGuard {
171 fn drop(&mut self) {
172 self.0.fetch_sub(1, Ordering::AcqRel);
173 }
174}
175
176fn run_task(f: BoxedDispatchable) {
178 if let Err(payload) = panic::catch_unwind(panic::AssertUnwindSafe(|| f.run())) {
179 log::error!("Blocking pool task panicked during completion");
180 std::mem::forget(payload);
182 }
183}
184
185#[cfg(any(target_os = "linux", target_os = "android"))]
190#[derive(Debug, Clone)]
191struct CpuMask(Option<Arc<[libc::c_ulong]>>);
192
193#[cfg(any(target_os = "linux", target_os = "android"))]
194impl CpuMask {
195 const SET_WORDS: usize = size_of::<libc::cpu_set_t>() / size_of::<libc::c_ulong>();
197
198 fn current() -> Self {
200 let mut words = Self::SET_WORDS;
201 loop {
202 let mut mask = vec![0; words];
203 let res = unsafe {
206 libc::sched_getaffinity(0, size_of_val(&mask[..]), mask.as_mut_ptr().cast())
207 };
208 if res == 0 {
209 return Self(Some(mask.into()));
210 }
211 let einval = std::io::Error::last_os_error().raw_os_error() == Some(libc::EINVAL);
213 if !einval || words >= Self::SET_WORDS << 10 {
214 return Self(None);
215 }
216 words *= 2;
217 }
218 }
219
220 fn apply(&self) {
222 if let Some(ref mask) = self.0 {
223 let _ =
228 unsafe { libc::sched_setaffinity(0, size_of_val(&mask[..]), mask.as_ptr().cast()) };
229 }
230 }
231}
232
233#[cfg(not(any(target_os = "linux", target_os = "android")))]
235#[derive(Debug, Clone)]
236struct CpuMask;
237
238#[cfg(not(any(target_os = "linux", target_os = "android")))]
239impl CpuMask {
240 fn current() -> Self {
241 CpuMask
242 }
243
244 #[allow(clippy::unused_self)]
245 fn apply(&self) {}
246}
247
248fn worker(
249 receiver_high_prio: Receiver<BoxedDispatchable>,
250 receiver_low_prio: Receiver<BoxedDispatchable>,
251 guard: CounterGuard,
252 thread_limit: usize,
253 timeout: Duration,
254 affinity: CpuMask,
255) -> impl FnOnce() {
256 move || {
257 affinity.apply();
258 let mut guard = guard;
259 let mut sel = Select::new_biased();
260 sel.recv(&receiver_high_prio);
261 sel.recv(&receiver_low_prio);
262 loop {
263 let task = match sel.select_timeout(timeout) {
264 Ok(op) if op.index() == 0 => op.recv(&receiver_high_prio),
265 Ok(op) => op.recv(&receiver_low_prio),
266 Err(_) => {
267 let counter = guard.0.clone();
270 drop(guard);
271 fence(Ordering::SeqCst);
272 if receiver_high_prio.is_empty() {
273 return;
274 }
275 match CounterGuard::reserve(&counter, thread_limit) {
276 Some((g, _)) => guard = g,
277 None => return,
278 }
279 continue;
280 }
281 };
282 if let Ok(f) = task {
283 run_task(f);
284 } else {
285 while let Ok(f) = receiver_high_prio.try_recv() {
288 run_task(f);
289 }
290 return;
291 }
292 }
293 }
294}
295
296#[derive(Debug, Clone)]
306pub struct ThreadPool {
307 name: String,
308 affinity: CpuMask,
309 sender_low_prio: Sender<BoxedDispatchable>,
310 receiver_low_prio: Receiver<BoxedDispatchable>,
311 sender_high_prio: Sender<BoxedDispatchable>,
312 receiver_high_prio: Receiver<BoxedDispatchable>,
313 counter: Arc<AtomicUsize>,
314 stats: Arc<PoolStats>,
315 thread_limit: usize,
316 recv_timeout: Duration,
317}
318
319impl ThreadPool {
320 pub fn new(name: &str, thread_limit: usize, recv_timeout: Duration) -> Self {
326 let (sender_low_prio, receiver_low_prio) = bounded(0);
327 let (sender_high_prio, receiver_high_prio) = unbounded();
328 Self {
329 sender_low_prio,
330 receiver_low_prio,
331 sender_high_prio,
332 receiver_high_prio,
333 thread_limit: thread_limit.max(1),
334 recv_timeout,
335 name: format!("{name}:pool-wrk"),
336 affinity: CpuMask::current(),
337 counter: Arc::new(AtomicUsize::new(0)),
338 stats: Arc::default(),
339 }
340 }
341
342 pub fn metrics(&self) -> PoolMetrics {
347 PoolMetrics {
348 thread_limit: self.thread_limit,
349 threads: self.counter.load(Ordering::Relaxed),
350 active_tasks: self.stats.active.load(Ordering::Relaxed),
351 queue_depth: self.receiver_high_prio.len(),
352 max_queue_depth: self.stats.max_queue.load(Ordering::Relaxed),
353 saturated_tasks: self.stats.saturated.load(Ordering::Relaxed),
354 tasks: self.stats.tasks.load(Ordering::Relaxed),
355 wait_duration: Duration::from_nanos(self.stats.wait.load(Ordering::Relaxed)),
356 busy_duration: Duration::from_nanos(self.stats.busy.load(Ordering::Relaxed)),
357 }
358 }
359
360 pub(crate) fn execute_inplace<F, R>(f: F) -> BlockingResult<R>
361 where
362 F: FnOnce() -> R + Send + 'static,
363 R: Send + 'static,
364 {
365 let (tx, rx) = oneshot::async_channel();
366 let result = panic::catch_unwind(panic::AssertUnwindSafe(f));
367 let _ = tx.send(result);
368 BlockingResult { rx, detached: None }
369 }
370
371 #[allow(clippy::missing_panics_doc)]
372 pub fn execute<F, R>(&self, f: F) -> BlockingResult<R>
384 where
385 F: FnOnce() -> R + Send + 'static,
386 R: Send + 'static,
387 {
388 let (tx, rx) = oneshot::async_channel();
389 let detached = Arc::new(AtomicBool::new(false));
390 let res = BlockingResult {
391 rx,
392 detached: Some(detached.clone()),
393 };
394 let stats = self.stats.clone();
395 let queued = Instant::now();
396 let f = Box::new(move || {
397 if !tx.is_closed() || {
400 fence(Ordering::Acquire);
401 detached.load(Ordering::Relaxed)
402 } {
403 let start = Instant::now();
404 stats.tasks.fetch_add(1, Ordering::Relaxed);
405 stats
406 .wait
407 .fetch_add(as_nanos(start - queued), Ordering::Relaxed);
408 stats.active.fetch_add(1, Ordering::Relaxed);
409
410 let result = panic::catch_unwind(panic::AssertUnwindSafe(f));
411
412 stats.active.fetch_sub(1, Ordering::Relaxed);
413 stats
414 .busy
415 .fetch_add(as_nanos(start.elapsed()), Ordering::Relaxed);
416 let _ = tx.send(result);
417 }
418 });
419
420 let f = match self.sender_low_prio.try_send(f) {
422 Ok(()) => return res,
423 Err(TrySendError::Full(f)) => f,
424 Err(TrySendError::Disconnected(_)) => {
425 unreachable!("receiver should not all disconnected")
426 }
427 };
428
429 self.sender_high_prio
430 .send(f)
431 .expect("the channel should not be closed");
432 self.stats
433 .max_queue
434 .fetch_max(self.receiver_high_prio.len(), Ordering::Relaxed);
435 fence(Ordering::SeqCst);
438
439 if let Some((guard, idx)) = CounterGuard::reserve(&self.counter, self.thread_limit) {
440 let result = thread::Builder::new()
441 .name(format!("{}:{}", self.name, idx))
442 .spawn(worker(
443 self.receiver_high_prio.clone(),
444 self.receiver_low_prio.clone(),
445 guard,
446 self.thread_limit,
447 self.recv_timeout,
448 self.affinity.clone(),
449 ));
450 if let Err(e) = result {
451 log::error!("Cannot start blocking pool thread: {e}");
452 while self.counter.load(Ordering::Acquire) == 0 {
455 if self.receiver_high_prio.try_recv().is_err() {
456 break;
457 }
458 }
459 }
460 } else {
461 self.stats.saturated.fetch_add(1, Ordering::Relaxed);
462 }
463 res
464 }
465}
466
467impl<R> Future for BlockingResult<R> {
468 type Output = Result<R, BlockingError>;
469
470 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
471 let this = self.get_mut();
472
473 match Pin::new(&mut this.rx).poll(cx) {
474 Poll::Pending => Poll::Pending,
475 Poll::Ready(result) => Poll::Ready(
476 result
477 .map_err(|_| BlockingError)
478 .and_then(|res| res.map_err(|_| BlockingError)),
479 ),
480 }
481 }
482}
483
484#[cfg(test)]
485#[path = "../tests/unit/pool.rs"]
486mod tests;