1use super::*;
2use embassy_executor::{SendSpawner, Spawner};
3
4pub type SpawnerIdentifier = usize;
5
6pub(super) struct SpawnerState {
7 pub executor: usize,
8 pub send: SendSpawner,
10 pub tasks: usize,
11 #[cfg(feature = "metrics")]
12 pub counters: &'static crate::metrics::ExecutorCounters,
13}
14
15#[cfg(any(
17 target_os = "linux",
18 target_os = "macos",
19 target_os = "windows",
20 target_arch = "wasm32"
21))]
22std::thread_local! {
23 static LOCAL_SPAWNER: core::cell::Cell<Option<Spawner>> = const { core::cell::Cell::new(None) };
24}
25
26impl Manager {
27 pub fn register_spawner(&'static self, spawner: Spawner) -> Result<SpawnerIdentifier> {
28 #[cfg(feature = "metrics")]
29 let counters = crate::metrics::ExecutorCounters::get(spawner.executor_id());
30 let identifier = self.1.lock(|spawners| {
31 let mut spawners = spawners.borrow_mut();
32 let identifier = Self::find_first_available_identifier(&spawners, 0..usize::MAX)
33 .ok_or(Error::TooManySpawners)?;
34 spawners.insert(
35 identifier,
36 SpawnerState {
37 executor: spawner.executor_id(),
38 send: spawner.make_send(),
39 tasks: 0,
40 #[cfg(feature = "metrics")]
41 counters,
42 },
43 );
44 Ok(identifier)
45 })?;
46 #[cfg(any(
47 target_os = "linux",
48 target_os = "macos",
49 target_os = "windows",
50 target_arch = "wasm32"
51 ))]
52 LOCAL_SPAWNER.set(Some(spawner));
53 Ok(identifier)
54 }
55
56 pub fn unregister_spawner(&'static self, identifier: SpawnerIdentifier) -> Result<()> {
58 self.1.lock(|spawners| {
59 let mut spawners = spawners.borrow_mut();
60 let state = spawners.get(&identifier).ok_or(Error::NoSpawnerAvailable)?;
61 if state.tasks != 0 {
62 return Err(Error::AlreadySet);
63 }
64 spawners.remove(&identifier);
65 Ok(())
66 })
67 }
68
69 pub(super) async fn local_spawner() -> Result<Spawner> {
70 if Self::get_current_internal_identifier().await.is_ok() {
72 return Ok(unsafe { Spawner::for_current_executor().await });
73 }
74 #[cfg(any(
75 target_os = "linux",
76 target_os = "macos",
77 target_os = "windows",
78 target_arch = "wasm32"
79 ))]
80 if let Some(spawner) = LOCAL_SPAWNER.get() {
81 return Ok(spawner);
82 }
83 Err(Error::ThreadNotRegistered)
84 }
85
86 pub(super) fn reserve_spawner(
92 &self,
93 executor: Option<usize>,
94 requested: Option<SpawnerIdentifier>,
95 ) -> Result<(SpawnerIdentifier, SendSpawner)> {
96 self.1.lock(|spawners| {
97 let mut spawners = spawners.borrow_mut();
98 let eligible = |state: &SpawnerState| executor.is_none_or(|e| state.executor == e);
99 let (identifier, state) = match requested {
100 Some(identifier) => spawners
101 .get_mut(&identifier)
102 .filter(|state| eligible(state))
103 .map(|state| (identifier, state))
104 .ok_or(Error::InvalidSpawnerIdentifier)?,
105 None => spawners
106 .iter_mut()
107 .filter(|(_, state)| eligible(state))
108 .min_by_key(|(_, state)| state.tasks)
109 .map(|(identifier, state)| (*identifier, state))
110 .ok_or(Error::NoSpawnerAvailable)?,
111 };
112 state.tasks += 1;
113 Ok((identifier, state.send))
114 })
115 }
116
117 #[cfg(feature = "metrics")]
119 pub(super) fn spawner_counters(
120 &self,
121 identifier: SpawnerIdentifier,
122 ) -> &'static crate::metrics::ExecutorCounters {
123 self.1
124 .lock(|spawners| spawners.borrow()[&identifier].counters)
125 }
126
127 pub(super) fn release_spawner(&self, identifier: SpawnerIdentifier) {
129 self.1.lock(|spawners| {
130 if let Some(state) = spawners.borrow_mut().get_mut(&identifier) {
131 state.tasks -= 1;
132 }
133 });
134 }
135
136 pub async fn get_spawner(&self, task: TaskIdentifier) -> Result<SpawnerIdentifier> {
137 Self::get_task(&*self.0.read().await, task).map(|task| task.spawner_identifier)
138 }
139}