Skip to main content

ntex_rt/
pool.rs

1//! A thread pool for blocking operations.
2use 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
10/// Submits blocking work and returns a future for its result.
11///
12/// If a system is running, work is submitted to the blocking thread pool of
13/// the current arbiter, see [`System::spawn_blocking`](crate::System::spawn_blocking).
14/// Otherwise, the closure runs immediately on the current thread.
15/// Panics from the closure are captured and reported as [`BlockingError`]
16/// through the returned future in either case.
17///
18/// Dropping the returned future prevents queued work from starting, but cannot
19/// interrupt work that is already running. Call [`BlockingResult::detach`] to
20/// let queued work continue even if its result is no longer needed.
21pub 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/// Error returned when blocking work cannot produce a result.
33///
34/// This can occur if the task is canceled, panics, or no worker thread
35/// can be started.
36#[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/// Future resolving to the result of blocking work.
48///
49/// Resolves to `Ok(output)` or [`BlockingError`] if the work cannot produce a
50/// result, including a closure panic. Dropping this value cancels work that has
51/// not been picked up by a worker; it does not interrupt running work. Use
52/// [`detach`](Self::detach) to discard the result without canceling queued work.
53#[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    /// Detaches the task so it can continue without awaiting its result.
61    ///
62    /// Does not require a running runtime.
63    pub fn detach(self) {
64        if let Some(detached) = &self.detached {
65            // published by dropping the receiver
66            detached.store(true, Ordering::Relaxed);
67        }
68    }
69}
70
71/// Snapshot of [`ThreadPool`] metrics.
72///
73/// Durations and task counts are totals since the pool was created. Rates
74/// and averages over an interval are computed from the deltas of two
75/// snapshots, e.g. the average queue wait is the `wait_duration` delta
76/// divided by the `tasks` delta.
77///
78/// [`System::pool_metrics`](crate::System::pool_metrics) combines the pools
79/// of all arbiters: gauges, limits, and totals are summed and
80/// `max_queue_depth` is the highest of any single pool.
81#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
82#[non_exhaustive]
83pub struct PoolMetrics {
84    /// Maximum number of worker threads.
85    pub thread_limit: usize,
86    /// Number of worker threads, busy or idle.
87    pub threads: usize,
88    /// Number of tasks being executed.
89    pub active_tasks: usize,
90    /// Number of tasks waiting for a worker thread.
91    pub queue_depth: usize,
92    /// Highest number of tasks waiting for a worker thread at once.
93    pub max_queue_depth: usize,
94    /// Number of tasks queued while the pool was at its thread limit.
95    ///
96    /// A growing value means the pool has too few worker threads for its load.
97    pub saturated_tasks: u64,
98    /// Number of tasks started.
99    pub tasks: u64,
100    /// Total time started tasks waited for a worker thread.
101    pub wait_duration: Duration,
102    /// Total time worker threads spent executing tasks.
103    pub busy_duration: Duration,
104}
105
106impl PoolMetrics {
107    /// Adds the totals of another pool, keeping the highest queue depth.
108    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    /// Adds the limits, gauges, and totals of another pool.
117    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    // nanoseconds
133    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
156/// Reserved worker slot, released on drop.
157struct 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
176/// Runs a task, keeping the worker alive if result delivery or disposal panics.
177fn 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        // the payload destructor may panic as well
181        std::mem::forget(payload);
182    }
183}
184
185/// CPU affinity of the thread that created a pool.
186///
187/// A new thread inherits the affinity of the thread that starts it, usually a
188/// pinned arbiter submitting work. Workers restore the creator's affinity.
189#[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    /// Words of a `cpu_set_t`.
196    const SET_WORDS: usize = size_of::<libc::cpu_set_t>() / size_of::<libc::c_ulong>();
197
198    /// Returns the CPU mask of the current thread.
199    fn current() -> Self {
200        let mut words = Self::SET_WORDS;
201        loop {
202            let mut mask = vec![0; words];
203            // SAFETY: the kernel writes at most `size_of_val(mask)` bytes,
204            // the mask has the layout of a larger `cpu_set_t`
205            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            // the kernel mask is larger than `cpu_set_t`
212            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    /// Sets the CPU mask of the current thread.
221    fn apply(&self) {
222        if let Some(ref mask) = self.0 {
223            // on failure, for example after a cpuset change, the thread keeps
224            // the inherited mask
225            // SAFETY: the kernel reads `size_of_val(mask)` bytes, the mask has
226            // the layout of a larger `cpu_set_t`
227            let _ =
228                unsafe { libc::sched_setaffinity(0, size_of_val(&mask[..]), mask.as_ptr().cast()) };
229        }
230    }
231}
232
233/// Other platforms do not restore the creator's affinity.
234#[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                    // release the slot, then pick up work queued meanwhile,
268                    // pairs with the fence in `ThreadPool::execute`
269                    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                // the pool is dropped and the channels stay selectable,
286                // run the queued work and exit
287                while let Ok(f) = receiver_high_prio.try_recv() {
288                    run_task(f);
289                }
290                return;
291            }
292        }
293    }
294}
295
296/// A thread pool for executing blocking operations.
297///
298/// The number of worker threads scales dynamically with load, but will
299/// never exceed the `thread_limit` parameter. When all worker threads are
300/// busy, tasks enter an unbounded queue until a worker becomes available.
301/// Clones share the workers, queue, and metrics.
302///
303/// On Linux and Android, workers run with the CPU affinity of the thread that
304/// created the pool, not of the thread whose submission started them.
305#[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    /// Creates a pool with a worker limit and idle-worker timeout.
321    ///
322    /// Workers are started on demand and named using `name`. An idle worker
323    /// exits after `recv_timeout` without work. A `thread_limit` of zero is
324    /// treated as one.
325    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    /// Returns a snapshot of the pool metrics.
343    ///
344    /// Gauges and totals are read independently and may be slightly
345    /// inconsistent with each other.
346    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    /// Submits a closure to the thread pool.
373    ///
374    /// The task will be executed by an available worker thread. If no threads
375    /// are available and the pool has reached its maximum size, the work will
376    /// be queued until a worker thread becomes available. Submission does not
377    /// wait for the closure to run or for a worker slot, though it may start an
378    /// OS thread.
379    ///
380    /// Dropping the result cancels work not yet picked up by a worker; use
381    /// [`BlockingResult::detach`] to keep that work queued. Closure panics and
382    /// failures to start a worker when none is available yield [`BlockingError`].
383    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            // do not execute operation if receiver is dropped, unless detached,
398            // the fence pairs with the receiver drop in `detach`
399            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        // hand over to an idle worker
421        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        // pairs with the fence in `worker`, either an exiting worker sees
436        // the queued task or a free slot is visible here
437        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                // no worker can run queued tasks, drop them so they
453                // resolve with `BlockingError`
454                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;