embassy_executor/raw/mod.rs
1//! Raw executor.
2//!
3//! This module exposes "raw" Executor and Task structs for more low level control.
4//!
5//! ## WARNING: here be dragons!
6//!
7//! Using this module requires respecting subtle safety contracts. If you can, prefer using the safe
8//! [executor wrappers](crate::Executor) and the [`embassy_executor::task`](embassy_executor_macros::task) macro, which are fully safe.
9
10mod run_queue;
11
12#[cfg_attr(all(cortex_m, target_has_atomic = "32"), path = "state_atomics_arm.rs")]
13#[cfg_attr(
14 all(not(cortex_m), any(target_has_atomic = "8", target_has_atomic = "32")),
15 path = "state_atomics.rs"
16)]
17#[cfg_attr(
18 not(any(target_has_atomic = "8", target_has_atomic = "32")),
19 path = "state_critical_section.rs"
20)]
21mod state;
22
23#[cfg(feature = "trace")]
24pub mod trace;
25pub(crate) mod util;
26#[cfg_attr(feature = "turbowakers", path = "waker_turbo.rs")]
27mod waker;
28
29#[cfg(feature = "scheduler-deadline")]
30mod deadline;
31
32use core::future::Future;
33use core::marker::PhantomData;
34use core::mem;
35use core::pin::Pin;
36use core::ptr::NonNull;
37#[cfg(not(feature = "portable-atomic"))]
38use core::sync::atomic::AtomicPtr;
39use core::sync::atomic::Ordering;
40use core::task::{Context, Poll, Waker};
41
42#[cfg(feature = "scheduler-deadline")]
43pub(crate) use deadline::Deadline;
44use embassy_executor_timer_queue::TimerQueueItem;
45#[cfg(feature = "portable-atomic")]
46use portable_atomic::AtomicPtr;
47
48use self::run_queue::{RunQueue, RunQueueItem};
49use self::state::State;
50use self::util::{SyncUnsafeCell, UninitCell};
51pub use self::waker::task_from_waker;
52use self::waker::try_task_from_waker;
53use super::SpawnToken;
54use crate::{ExecutorId, Metadata, MetadataRef, SpawnError, TaskId};
55
56struct TimerQueueItemProviderImpl;
57
58impl embassy_executor_timer_queue::TimerQueueItemProvider for TimerQueueItemProviderImpl {
59 unsafe fn item_from_waker(waker: &Waker) -> &'static mut TimerQueueItem {
60 unsafe { task_from_waker(waker).timer_queue_item() }
61 }
62
63 unsafe fn try_item_from_waker(waker: &Waker) -> Option<&'static mut TimerQueueItem> {
64 unsafe { try_task_from_waker(waker).map(|task| task.timer_queue_item()) }
65 }
66}
67
68embassy_executor_timer_queue::timer_queue_item_provider_impl!(TimerQueueItemProviderImpl);
69
70/// Raw task header for use in task pointers.
71///
72/// A task can be in one of the following states:
73///
74/// - Not spawned: the task is ready to spawn.
75/// - `SPAWNED`: the task is currently spawned and may be running.
76/// - `RUN_ENQUEUED`: the task is enqueued to be polled. Note that the task may be `!SPAWNED`.
77/// In this case, the `RUN_ENQUEUED` state will be cleared when the task is next polled, without
78/// polling the task's future.
79///
80/// A task's complete life cycle is as follows:
81///
82/// ```text
83/// ┌────────────┐ ┌────────────────────────┐
84/// │Not spawned │◄─5┤Not spawned|Run enqueued│
85/// │ ├6─►│ │
86/// └─────┬──────┘ └──────▲─────────────────┘
87/// 1 │
88/// │ ┌────────────┘
89/// │ 4
90/// ┌─────▼────┴─────────┐
91/// │Spawned|Run enqueued│
92/// │ │
93/// └─────┬▲─────────────┘
94/// 2│
95/// │3
96/// ┌─────▼┴─────┐
97/// │ Spawned │
98/// │ │
99/// └────────────┘
100/// ```
101///
102/// Transitions:
103/// - 1: Task is spawned - `AvailableTask::claim -> Executor::spawn`
104/// - 2: During poll - `RunQueue::dequeue_all -> State::run_dequeue`
105/// - 3: Task wakes itself, waker wakes task, or task exits - `Waker::wake -> wake_task -> State::run_enqueue`
106/// - 4: A run-queued task exits - `TaskStorage::poll -> Poll::Ready`
107/// - 5: Task is dequeued. The task's future is not polled, because exiting the task replaces its `poll_fn`.
108/// - 6: A task is waken when it is not spawned - `wake_task -> State::run_enqueue`
109pub(crate) struct TaskHeader {
110 pub(crate) state: State,
111 pub(crate) run_queue_item: RunQueueItem,
112
113 pub(crate) executor: AtomicPtr<SyncExecutor>,
114 poll_fn: SyncUnsafeCell<Option<unsafe fn(TaskRef)>>,
115
116 /// Integrated timer queue storage. This field should not be accessed outside of the timer queue.
117 pub(crate) timer_queue_item: TimerQueueItem,
118
119 pub(crate) metadata: Metadata,
120}
121
122/// This is essentially a `&'static TaskStorage<F>` where the type of the future has been erased.
123#[derive(Debug, Clone, Copy, PartialEq)]
124pub struct TaskRef {
125 ptr: NonNull<TaskHeader>,
126}
127
128unsafe impl Send for TaskRef where &'static TaskHeader: Send {}
129unsafe impl Sync for TaskRef where &'static TaskHeader: Sync {}
130
131impl TaskRef {
132 fn new<F: Future + 'static>(task: &'static TaskStorage<F>) -> Self {
133 Self {
134 ptr: NonNull::from(task).cast(),
135 }
136 }
137
138 /// Safety: The pointer must have been obtained with `Task::as_ptr`
139 pub(crate) unsafe fn from_ptr(ptr: *const TaskHeader) -> Self {
140 Self {
141 ptr: NonNull::new_unchecked(ptr as *mut TaskHeader),
142 }
143 }
144
145 pub(crate) fn header(self) -> &'static TaskHeader {
146 unsafe { self.ptr.as_ref() }
147 }
148
149 /// Get the metadata of this task
150 pub fn metadata(self) -> MetadataRef {
151 MetadataRef::new(self)
152 }
153
154 /// Returns a reference to the executor that the task is currently running on.
155 pub unsafe fn executor(self) -> Option<&'static Executor> {
156 let executor = self.header().executor.load(Ordering::Relaxed);
157 executor.as_ref().map(|e| Executor::wrap(e))
158 }
159
160 /// Get the id of the executor the task is currently running on.
161 /// None when the task is not running.
162 pub fn executor_id(self) -> Option<ExecutorId> {
163 unsafe { self.executor().map(|e| e.id()) }
164 }
165
166 /// Returns a mutable reference to the timer queue item.
167 ///
168 /// Safety
169 ///
170 /// This function must only be called in the context of the integrated timer queue.
171 pub unsafe fn timer_queue_item(mut self) -> &'static mut TimerQueueItem {
172 unsafe { &mut self.ptr.as_mut().timer_queue_item }
173 }
174
175 /// The returned pointer is valid for the entire TaskStorage.
176 pub(crate) fn as_ptr(self) -> *const TaskHeader {
177 self.ptr.as_ptr()
178 }
179
180 /// An opaque pointer identifying this task.
181 ///
182 /// Lets a `TaskRef` be stored where only one word fits. Recover it with [`from_raw`](Self::from_raw).
183 ///
184 /// The pointer must not be dereferenced.
185 pub fn as_raw(self) -> NonNull<()> {
186 self.ptr.cast()
187 }
188
189 /// Recover the task that [`as_raw`](Self::as_raw) was called on.
190 ///
191 /// # Safety
192 ///
193 /// `ptr` must have been returned by `as_raw`.
194 pub unsafe fn from_raw(ptr: NonNull<()>) -> Self {
195 Self { ptr: ptr.cast() }
196 }
197
198 /// Returns the task ID.
199 /// This can be used in combination with trace to match task names with IDs
200 pub fn id(&self) -> TaskId {
201 TaskId(self.as_ptr() as usize)
202 }
203}
204
205/// Raw storage in which a task can be spawned.
206///
207/// This struct holds the necessary memory to spawn one task whose future is `F`.
208/// At a given time, the `TaskStorage` may be in spawned or not-spawned state. You
209/// may spawn it with [`TaskStorage::spawn()`], which will fail if it is already spawned.
210///
211/// A `TaskStorage` must live forever, it may not be deallocated even after the task has finished
212/// running. Hence the relevant methods require `&'static self`. It may be reused, however.
213///
214/// Internally, the [embassy_executor::task](embassy_executor_macros::task) macro allocates an array of `TaskStorage`s
215/// in a `static`. The most common reason to use the raw `Task` is to have control of where
216/// the memory for the task is allocated: on the stack, or on the heap with e.g. `Box::leak`, etc.
217
218// repr(C) is needed to guarantee that the Task is located at offset 0
219// This makes it safe to cast between TaskHeader and TaskStorage pointers.
220#[repr(C)]
221pub struct TaskStorage<F: Future + 'static> {
222 raw: TaskHeader,
223 future: UninitCell<F>, // Valid if STATE_SPAWNED
224}
225
226unsafe fn poll_exited(_p: TaskRef) {
227 // Nothing to do, the task is already !SPAWNED and dequeued.
228}
229
230impl<F: Future + 'static> TaskStorage<F> {
231 const NEW: Self = Self::new();
232
233 /// Create a new TaskStorage, in not-spawned state.
234 pub const fn new() -> Self {
235 Self {
236 raw: TaskHeader {
237 state: State::new(),
238 run_queue_item: RunQueueItem::new(),
239 executor: AtomicPtr::new(core::ptr::null_mut()),
240 // Note: this is lazily initialized so that a static `TaskStorage` will go in `.bss`
241 poll_fn: SyncUnsafeCell::new(None),
242
243 timer_queue_item: TimerQueueItem::new(),
244 metadata: Metadata::new(),
245 },
246 future: UninitCell::uninit(),
247 }
248 }
249
250 /// Try to spawn the task.
251 ///
252 /// The `future` closure constructs the future. It's only called if spawning is
253 /// actually possible. It is a closure instead of a simple `future: F` param to ensure
254 /// the future is constructed in-place, avoiding a temporary copy in the stack thanks to
255 /// NRVO optimizations.
256 ///
257 /// This function will fail if the task is already spawned and has not finished running.
258 /// In this case, [`SpawnError::Busy`] is returned.
259 ///
260 /// Once the task has finished running, you may spawn it again. It is allowed to spawn it
261 /// on a different executor.
262 pub fn spawn(&'static self, future: impl FnOnce() -> F) -> Result<SpawnToken<impl Sized>, SpawnError> {
263 let task = AvailableTask::claim(self);
264 match task {
265 Some(task) => Ok(task.initialize(future)),
266 None => Err(SpawnError::Busy),
267 }
268 }
269
270 unsafe fn poll(p: TaskRef) {
271 let this = &*p.as_ptr().cast::<TaskStorage<F>>();
272
273 let future = Pin::new_unchecked(this.future.as_mut());
274 let waker = waker::from_task(p);
275 let mut cx = Context::from_waker(&waker);
276 match future.poll(&mut cx) {
277 Poll::Ready(_) => {
278 #[cfg(feature = "trace")]
279 let exec_ptr: *const SyncExecutor = this.raw.executor.load(Ordering::Relaxed);
280
281 // As the future has finished and this function will not be called
282 // again, we can safely drop the future here.
283 this.future.drop_in_place();
284
285 // We replace the poll_fn with a despawn function, so that the task is cleaned up
286 // when the executor polls it next.
287 this.raw.poll_fn.set(Some(poll_exited));
288
289 // Make sure we despawn last, so that other threads can only spawn the task
290 // after we're done with it.
291 this.raw.state.despawn();
292
293 #[cfg(feature = "trace")]
294 trace::TraceImpl::task_end(unsafe { &*exec_ptr }.id(), p);
295 }
296 Poll::Pending => {}
297 }
298
299 // the compiler is emitting a virtual call for waker drop, but we know
300 // it's a noop for our waker.
301 mem::forget(waker);
302 }
303
304 #[doc(hidden)]
305 #[allow(dead_code)]
306 fn _assert_sync(self) {
307 fn assert_sync<T: Sync>(_: T) {}
308
309 assert_sync(self)
310 }
311}
312
313/// An uninitialized [`TaskStorage`].
314pub struct AvailableTask<F: Future + 'static> {
315 task: &'static TaskStorage<F>,
316}
317
318impl<F: Future + 'static> AvailableTask<F> {
319 /// Try to claim a [`TaskStorage`].
320 ///
321 /// This function returns `None` if a task has already been spawned and has not finished running.
322 pub fn claim(task: &'static TaskStorage<F>) -> Option<Self> {
323 task.raw.state.spawn().then(|| Self { task })
324 }
325
326 fn initialize_impl<S>(self, name: Option<&'static str>, future: impl FnOnce() -> F) -> SpawnToken<S> {
327 unsafe {
328 self.task.raw.metadata.init(name);
329 self.task.raw.poll_fn.set(Some(TaskStorage::<F>::poll));
330 self.task.future.write_in_place(future);
331
332 let task = TaskRef::new(self.task);
333
334 SpawnToken::new(task)
335 }
336 }
337
338 /// Initialize the [`TaskStorage`] to run the given future.
339 pub fn initialize(self, future: impl FnOnce() -> F) -> SpawnToken<F> {
340 self.initialize_impl::<F>(None, future)
341 }
342
343 /// Initialize the [`TaskStorage`] to run the given future.
344 ///
345 /// # Safety
346 ///
347 /// `future` must be a closure of the form `move || my_async_fn(args)`, where `my_async_fn`
348 /// is an `async fn`, NOT a hand-written `Future`.
349 #[doc(hidden)]
350 pub unsafe fn __initialize_async_fn<FutFn>(self, future: impl FnOnce() -> F) -> SpawnToken<FutFn> {
351 // When send-spawning a task, we construct the future in this thread, and effectively
352 // "send" it to the executor thread by enqueuing it in its queue. Therefore, in theory,
353 // send-spawning should require the future `F` to be `Send`.
354 //
355 // The problem is this is more restrictive than needed. Once the future is executing,
356 // it is never sent to another thread. It is only sent when spawning. It should be
357 // enough for the task's arguments to be Send. (and in practice it's super easy to
358 // accidentally make your futures !Send, for example by holding an `Rc` or a `&RefCell` across an `.await`.)
359 //
360 // We can do it by sending the task args and constructing the future in the executor thread
361 // on first poll. However, this cannot be done in-place, so it'll waste stack space for a copy
362 // of the args.
363 //
364 // Luckily, an `async fn` future contains just the args when freshly constructed. So, if the
365 // args are Send, it's OK to send a !Send future, as long as we do it before first polling it.
366 //
367 // (Note: this is how the generators are implemented today, it's not officially guaranteed yet,
368 // but it's possible it'll be guaranteed in the future. See zulip thread:
369 // https://rust-lang.zulipchat.com/#narrow/stream/187312-wg-async/topic/.22only.20before.20poll.22.20Send.20futures )
370 //
371 // The `FutFn` captures all the args, so if it's Send, the task can be send-spawned.
372 // This is why we return `SpawnToken<FutFn>` below.
373 //
374 // This ONLY holds for `async fn` futures. The other `spawn` methods can be called directly
375 // by the user, with arbitrary hand-implemented futures. This is why these return `SpawnToken<F>`.
376 self.initialize_impl::<FutFn>(None, future)
377 }
378}
379
380/// Raw storage that can hold up to N tasks of the same type.
381///
382/// This is essentially a `[TaskStorage<F>; N]`.
383pub struct TaskPool<F: Future + 'static, const N: usize> {
384 pool: [TaskStorage<F>; N],
385}
386
387impl<F: Future + 'static, const N: usize> TaskPool<F, N> {
388 /// Create a new TaskPool, with all tasks in non-spawned state.
389 pub const fn new() -> Self {
390 Self {
391 pool: [TaskStorage::NEW; N],
392 }
393 }
394
395 fn spawn_impl<T>(
396 &'static self,
397 name: Option<&'static str>,
398 future: impl FnOnce() -> F,
399 ) -> Result<SpawnToken<T>, SpawnError> {
400 match self.pool.iter().find_map(AvailableTask::claim) {
401 Some(task) => Ok(task.initialize_impl::<T>(name, future)),
402 None => Err(SpawnError::Busy),
403 }
404 }
405
406 /// Try to spawn a task in the pool.
407 ///
408 /// See [`TaskStorage::spawn()`] for details.
409 ///
410 /// This will loop over the pool and spawn the task in the first storage that
411 /// is currently free. If none is free, [`SpawnError::Busy`] is returned.
412 pub fn spawn(&'static self, future: impl FnOnce() -> F) -> Result<SpawnToken<impl Sized>, SpawnError> {
413 self.spawn_impl::<F>(None, future)
414 }
415
416 /// Like spawn(), but with `name` as the task's default name (see `MetadataRef::name`).
417 ///
418 /// Not covered by semver guarantees. DO NOT call this directly. Intended to be used
419 /// by the Embassy macros ONLY.
420 #[doc(hidden)]
421 pub fn _spawn(
422 &'static self,
423 name: Option<&'static str>,
424 future: impl FnOnce() -> F,
425 ) -> Result<SpawnToken<impl Sized>, SpawnError> {
426 self.spawn_impl::<F>(name, future)
427 }
428
429 /// Like spawn(), but allows the task to be send-spawned if the args are Send even if
430 /// the future is !Send, and with `name` as the task's default name (see `MetadataRef::name`).
431 ///
432 /// Not covered by semver guarantees. DO NOT call this directly. Intended to be used
433 /// by the Embassy macros ONLY.
434 ///
435 /// SAFETY: `future` must be a closure of the form `move || my_async_fn(args)`, where `my_async_fn`
436 /// is an `async fn`, NOT a hand-written `Future`.
437 #[doc(hidden)]
438 pub unsafe fn _spawn_async_fn<FutFn>(
439 &'static self,
440 name: Option<&'static str>,
441 future: FutFn,
442 ) -> Result<SpawnToken<impl Sized>, SpawnError>
443 where
444 FutFn: FnOnce() -> F,
445 {
446 // See the comment in AvailableTask::__initialize_async_fn for explanation.
447 self.spawn_impl::<FutFn>(name, future)
448 }
449}
450
451#[derive(Clone, Copy)]
452pub(crate) struct Pender(*mut ());
453
454unsafe impl Send for Pender {}
455unsafe impl Sync for Pender {}
456
457impl Pender {
458 pub(crate) fn pend(self) {
459 crate::pender::PenderImpl::pend(self.0);
460 }
461}
462
463pub(crate) struct SyncExecutor {
464 run_queue: RunQueue,
465 pender: Pender,
466}
467
468impl SyncExecutor {
469 pub(crate) fn new(pender: Pender) -> Self {
470 Self {
471 run_queue: RunQueue::new(),
472 pender,
473 }
474 }
475
476 /// Enqueue a task in the task queue
477 ///
478 /// # Safety
479 /// - `task` must be a valid pointer to a spawned task.
480 /// - `task` must be set up to run in this executor.
481 /// - `task` must NOT be already enqueued (in this executor or another one).
482 #[inline(always)]
483 unsafe fn enqueue(&'static self, task: TaskRef, l: state::Token) {
484 #[cfg(feature = "trace")]
485 trace::TraceImpl::task_ready_begin(self.id(), task);
486
487 if self.run_queue.enqueue(task, l) {
488 self.pender.pend();
489 }
490 }
491
492 pub(super) unsafe fn spawn(&'static self, task: TaskRef) {
493 task.header()
494 .executor
495 .store((self as *const Self).cast_mut(), Ordering::Relaxed);
496
497 #[cfg(feature = "trace")]
498 trace::TraceImpl::task_new(self.id(), task);
499
500 state::locked(|l| {
501 self.enqueue(task, l);
502 })
503 }
504
505 /// # Safety
506 ///
507 /// Same as [`Executor::poll`], plus you must only call this on the thread this executor was created.
508 pub(crate) unsafe fn poll(&'static self) {
509 #[cfg(feature = "trace")]
510 trace::TraceImpl::poll_start(self.id());
511
512 self.run_queue.dequeue_all(|p| {
513 let task = p.header();
514
515 #[cfg(feature = "trace")]
516 trace::TraceImpl::task_exec_begin(self.id(), p);
517
518 // Run the task
519 task.poll_fn.get().unwrap_unchecked()(p);
520
521 #[cfg(feature = "trace")]
522 trace::TraceImpl::task_exec_end(self.id(), p);
523 });
524
525 #[cfg(feature = "trace")]
526 trace::TraceImpl::executor_idle(self.id())
527 }
528
529 /// Get a unique ID for this Executor.
530 pub fn id(&'static self) -> ExecutorId {
531 ExecutorId(self as *const Self as usize)
532 }
533}
534
535/// Raw executor.
536///
537/// This is the core of the Embassy executor. It is low-level, requiring manual
538/// handling of wakeups and task polling. If you can, prefer using one of the
539/// [higher level executors](crate::Executor).
540///
541/// The raw executor leaves it up to you to handle wakeups and scheduling:
542///
543/// - To get the executor to do work, call `poll()`. This will poll all queued tasks (all tasks
544/// that "want to run").
545/// - You must supply a pender, as shown below. The executor will call it to notify you
546/// it has work to do. You must arrange for `poll()` to be called as soon as possible.
547/// - Enabling `platform-xx` features will define a pender for you. This means that you
548/// are limited to using the executors provided to you by the architecture/platform
549/// implementation. If you need a different executor, you must not enable `platform-xx` features.
550///
551/// The pender can be called from *any* context: any thread, any interrupt priority
552/// level, etc. It may be called synchronously from any `Executor` method call as well.
553/// You must deal with this correctly.
554///
555/// In particular, you must NOT call `poll` directly from the pender callback, as this violates
556/// the requirement for `poll` to not be called reentrantly.
557///
558/// The pender is supplied by implementing the [`Pender`](crate::pender::Pender) trait and
559/// registering it with the [`pender_impl!`](crate::pender_impl) macro:
560///
561/// ```rust
562/// struct MyPender;
563///
564/// impl embassy_executor::pender::Pender for MyPender {
565/// fn pend(context: *mut ()) {
566/// // schedule `poll()` to be called
567/// }
568/// }
569///
570/// embassy_executor::pender_impl!(MyPender);
571/// ```
572///
573/// The `context` argument is a piece of arbitrary data the executor will pass to the pender.
574/// You can set the `context` when calling [`Executor::new()`]. You can use it to, for example,
575/// differentiate between executors, or to pass a pointer to a callback that should be called.
576#[repr(transparent)]
577pub struct Executor {
578 pub(crate) inner: SyncExecutor,
579
580 _not_sync: PhantomData<*mut ()>,
581}
582
583impl Executor {
584 pub(crate) unsafe fn wrap(inner: &SyncExecutor) -> &Self {
585 mem::transmute(inner)
586 }
587
588 /// Create a new executor.
589 ///
590 /// When the executor has work to do, it will call the pender function and pass `context` to it.
591 ///
592 /// See [`Executor`] docs for details on the pender.
593 pub fn new(context: *mut ()) -> Self {
594 Self {
595 inner: SyncExecutor::new(Pender(context)),
596 _not_sync: PhantomData,
597 }
598 }
599
600 /// Spawn a task in this executor.
601 ///
602 /// # Safety
603 ///
604 /// `task` must be a valid pointer to an initialized but not-already-spawned task.
605 ///
606 /// It is OK to use `unsafe` to call this from a thread that's not the executor thread.
607 /// In this case, the task's Future must be Send. This is because this is effectively
608 /// sending the task to the executor thread.
609 pub(super) unsafe fn spawn(&'static self, task: TaskRef) {
610 self.inner.spawn(task)
611 }
612
613 /// Poll all queued tasks in this executor.
614 ///
615 /// This loops over all tasks that are queued to be polled (i.e. they're
616 /// freshly spawned or they've been woken). Other tasks are not polled.
617 ///
618 /// You must call `poll` after receiving a call to the pender. It is OK
619 /// to call `poll` even when not requested by the pender, but it wastes
620 /// energy.
621 ///
622 /// # Safety
623 ///
624 /// You must NOT call `poll` reentrantly on the same executor.
625 ///
626 /// In particular, note that `poll` may call the pender synchronously. Therefore, you
627 /// must NOT directly call `poll()` from the pender callback. Instead, the callback has to
628 /// somehow schedule for `poll()` to be called later, at a time you know for sure there's
629 /// no `poll()` already running.
630 pub unsafe fn poll(&'static self) {
631 self.inner.poll()
632 }
633
634 /// Get a spawner that spawns tasks in this executor.
635 ///
636 /// It is OK to call this method multiple times to obtain multiple
637 /// `Spawner`s. You may also copy `Spawner`s.
638 pub fn spawner(&'static self) -> super::Spawner {
639 super::Spawner::new(self)
640 }
641
642 /// Get a unique ID for this Executor.
643 pub fn id(&'static self) -> ExecutorId {
644 self.inner.id()
645 }
646}
647
648/// Wake a task by `TaskRef`.
649///
650/// You can obtain a `TaskRef` from a `Waker` using [`task_from_waker`].
651pub fn wake_task(task: TaskRef) {
652 let header = task.header();
653 header.state.run_enqueue(|l| {
654 // We have just marked the task as scheduled, so enqueue it.
655 unsafe {
656 let executor = header.executor.load(Ordering::Relaxed).as_ref().unwrap_unchecked();
657 executor.enqueue(task, l);
658 }
659 });
660}
661
662/// Wake a task by `TaskRef` without calling pend.
663///
664/// You can obtain a `TaskRef` from a `Waker` using [`task_from_waker`].
665pub fn wake_task_no_pend(task: TaskRef) {
666 let header = task.header();
667 header.state.run_enqueue(|l| {
668 // We have just marked the task as scheduled, so enqueue it.
669 unsafe {
670 let executor = header.executor.load(Ordering::Relaxed).as_ref().unwrap_unchecked();
671 executor.run_queue.enqueue(task, l);
672 }
673 });
674}