async_rt/
tracker.rs

1use crate::{Executor, JoinHandle};
2use std::fmt::Debug;
3use std::future::Future;
4use std::pin::Pin;
5use std::sync::atomic::AtomicUsize;
6use std::sync::Arc;
7use std::task::{Context, Poll};
8
9/// Track running tasks.
10///
11/// Note that there is no guarantee that the runtime would drop the future after it is done; therefore,
12/// this should only be used for purely approx statistics and not actual numbers. Additionally,
13/// it does not track any tasks spawned directly by the runtime but only by [`Executor::spawn`] through
14/// this struct.
15pub struct TrackerExecutor<E> {
16    executor: E,
17    counter: Arc<AtomicUsize>,
18}
19
20impl<E> Debug for TrackerExecutor<E> {
21    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
22        f.debug_struct("TrackerExecutor").finish()
23    }
24}
25
26impl<E: Executor> TrackerExecutor<E> {
27    pub fn new(executor: E) -> Self {
28        Self {
29            executor,
30            counter: Arc::default(),
31        }
32    }
33
34    /// Number of active tasks.
35    pub fn count(&self) -> usize {
36        self.counter.load(std::sync::atomic::Ordering::SeqCst)
37    }
38}
39
40struct FutureCounter<F> {
41    future: F,
42    counter: Arc<AtomicUsize>,
43}
44
45impl<F> FutureCounter<F> {
46    pub fn new(future: F, counter: Arc<AtomicUsize>) -> Self {
47        counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
48        Self { future, counter }
49    }
50}
51
52impl<F> Future for FutureCounter<F>
53where
54    F: Future + 'static + Unpin,
55{
56    type Output = F::Output;
57    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
58        Pin::new(&mut self.future).poll(cx)
59    }
60}
61
62impl<F> Drop for FutureCounter<F> {
63    fn drop(&mut self) {
64        self.counter
65            .fetch_sub(1, std::sync::atomic::Ordering::SeqCst);
66    }
67}
68
69impl<E: Executor> Executor for TrackerExecutor<E> {
70    fn spawn<F>(&self, future: F) -> JoinHandle<F::Output>
71    where
72        F: Future + Send + 'static,
73        F::Output: Send + 'static,
74    {
75        let counter = self.counter.clone();
76        let future = Box::pin(future);
77        let future = FutureCounter::new(future, counter);
78        self.executor.spawn(future)
79    }
80}
81
82#[cfg(test)]
83mod tests {
84    use super::TrackerExecutor;
85    use crate::rt::tokio::TokioExecutor;
86    use crate::Executor;
87    use std::future::Future;
88    use std::pin::Pin;
89    use std::task::{Context, Poll};
90
91    #[tokio::test]
92    async fn test_tracker_executor() {
93        let executor = TrackerExecutor::new(TokioExecutor);
94        let handle = executor.spawn(futures::future::pending::<()>());
95        assert_eq!(executor.count(), 1);
96        handle.abort();
97        // We yield back to the runtime to allow progress to be made after aborting the task.
98        crate::task::yield_now().await;
99        assert_eq!(executor.count(), 0);
100    }
101}