tokio/runtime/scheduler/multi_thread_alt/
handle.rs

1use crate::future::Future;
2use crate::loom::sync::Arc;
3use crate::runtime::scheduler::multi_thread_alt::worker;
4use crate::runtime::{
5    blocking, driver,
6    task::{self, JoinHandle},
7    TaskHooks, TaskMeta,
8};
9use crate::util::RngSeedGenerator;
10
11use std::fmt;
12
13cfg_unstable_metrics! {
14    mod metrics;
15}
16
17/// Handle to the multi thread scheduler
18pub(crate) struct Handle {
19    /// Task spawner
20    pub(super) shared: worker::Shared,
21
22    /// Resource driver handles
23    pub(crate) driver: driver::Handle,
24
25    /// Blocking pool spawner
26    pub(crate) blocking_spawner: blocking::Spawner,
27
28    /// Current random number generator seed
29    pub(crate) seed_generator: RngSeedGenerator,
30
31    /// User-supplied hooks to invoke for things
32    pub(crate) task_hooks: TaskHooks,
33}
34
35impl Handle {
36    /// Spawns a future onto the thread pool
37    pub(crate) fn spawn<F>(me: &Arc<Self>, future: F, id: task::Id) -> JoinHandle<F::Output>
38    where
39        F: crate::future::Future + Send + 'static,
40        F::Output: Send + 'static,
41    {
42        Self::bind_new_task(me, future, id)
43    }
44
45    pub(crate) fn shutdown(&self) {
46        self.shared.close(self);
47        self.driver.unpark();
48    }
49
50    pub(super) fn bind_new_task<T>(me: &Arc<Self>, future: T, id: task::Id) -> JoinHandle<T::Output>
51    where
52        T: Future + Send + 'static,
53        T::Output: Send + 'static,
54    {
55        let (handle, notified) = me.shared.owned.bind(future, me.clone(), id);
56
57        me.task_hooks.spawn(&TaskMeta {
58            #[cfg(tokio_unstable)]
59            id,
60            _phantom: Default::default(),
61        });
62
63        if let Some(notified) = notified {
64            me.shared.schedule_task(notified, false);
65        }
66
67        handle
68    }
69}
70
71cfg_unstable! {
72    use std::num::NonZeroU64;
73
74    impl Handle {
75        pub(crate) fn owned_id(&self) -> NonZeroU64 {
76            self.shared.owned.id
77        }
78    }
79}
80
81impl fmt::Debug for Handle {
82    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
83        fmt.debug_struct("multi_thread::Handle { ... }").finish()
84    }
85}