Skip to main content

http_type/task/
impl.rs

1use super::*;
2
3/// Creates a default Task instance.
4impl Default for Task {
5    /// Creates a default Task instance.
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - The default instance.
10    #[inline(always)]
11    fn default() -> Self {
12        let worker_count: usize = Handle::try_current()
13            .map(|handle: Handle| handle.metrics().num_workers())
14            .unwrap_or_default()
15            .max(1);
16        Self::new(worker_count)
17    }
18}
19
20/// Automatically shuts down the task pool when the last Task handle is dropped.
21impl Drop for Task {
22    /// Shuts down the task pool when the last Task handle is dropped.
23    #[inline(always)]
24    fn drop(&mut self) {
25        if Arc::strong_count(self.get_counter()) == 1 {
26            self.shutdown();
27        }
28    }
29}
30
31/// Inherent implementation of [`Task`].
32impl Task {
33    /// Creates a new Task instance.
34    ///
35    /// # Arguments
36    ///
37    /// - `usize` - The number of worker threads to spawn.
38    ///
39    /// # Returns
40    ///
41    /// - `Self` - The new instance.
42    pub fn new(worker_count: usize) -> Self {
43        let mut pool: Vec<UnboundedSender<AsyncTask>> = Vec::with_capacity(worker_count);
44        let counter: Arc<AtomicUsize> = Arc::new(AtomicUsize::new(0));
45        let shutdown: Arc<AtomicBool> = Arc::new(AtomicBool::new(false));
46        let notifies: Vec<Arc<Notify>> = (0..worker_count)
47            .map(|_: usize| Arc::new(Notify::new()))
48            .collect();
49        for notify in notifies.iter().take(worker_count) {
50            let (sender, mut receiver): (UnboundedSender<AsyncTask>, UnboundedReceiver<AsyncTask>) =
51                unbounded_channel();
52            pool.push(sender);
53            let shutdown_clone: Arc<AtomicBool> = shutdown.clone();
54            let notify_clone: Arc<Notify> = notify.clone();
55            spawn_blocking(move || {
56                Handle::current().block_on(LocalSet::new().run_until(async move {
57                    loop {
58                        if shutdown_clone.load(atomic::Ordering::Relaxed) {
59                            break;
60                        }
61                        match receiver.try_recv() {
62                            Ok(task) => {
63                                spawn_local(task);
64                            }
65                            Err(_) => {
66                                notify_clone.notified().await;
67                            }
68                        }
69                    }
70                }));
71            });
72        }
73        Self {
74            pool,
75            counter,
76            shutdown,
77            notifies,
78        }
79    }
80
81    /// Attempts to spawn a server task onto the global server task pool.
82    ///
83    /// This function sends the task to one of the worker threads in the pool.
84    /// The worker is selected using a round-robin algorithm based on an atomic counter,
85    /// or a forced index if provided.
86    ///
87    /// # Arguments
88    ///
89    /// - `Option<usize>` - An optional index to force selection of a specific worker.
90    ///   If None, the worker is selected using round-robin distribution.
91    /// - `F` - The future to spawn on the task pool, which requires the
92    ///   `Future<Output = ()> + Send + 'static` bound.
93    ///
94    /// # Returns
95    ///
96    /// - `bool` - true if the task was successfully sent, false otherwise.
97    pub fn try_spawn_local<F>(&self, index_opt: Option<usize>, hook: F) -> bool
98    where
99        F: Future<Output = ()> + Send + 'static,
100    {
101        if self.get_pool().is_empty() {
102            return false;
103        }
104        let index: usize = index_opt
105            .unwrap_or_else(|| self.get_counter().fetch_add(1, atomic::Ordering::Relaxed))
106            .wrapping_rem(self.get_pool().len());
107        if let Some(sender) = self.get_pool().get(index) {
108            let result: bool = sender.send(Box::pin(hook)).is_ok();
109            if result && let Some(notify) = self.get_notifies().get(index) {
110                notify.notify_one()
111            }
112            return result;
113        }
114        false
115    }
116
117    /// Shuts down the task pool.
118    ///
119    /// This function sets the shutdown flag and wakes all waiting worker threads,
120    /// causing them to exit their processing loops.
121    #[inline(always)]
122    pub fn shutdown(&self) {
123        self.get_shutdown().store(true, atomic::Ordering::Relaxed);
124        self.get_notifies()
125            .iter()
126            .for_each(|notify: &Arc<Notify>| notify.notify_one());
127    }
128}