From ab24e5db5927cf487ffb233e108a78007f2f3a18 Mon Sep 17 00:00:00 2001 From: Dario Nieuwenhuis Date: Wed, 12 Jan 2022 16:30:37 +0100 Subject: [PATCH] embassy/util: Add yield_now() --- embassy/src/util/mod.rs | 4 ++++ embassy/src/util/yield_now.rs | 25 +++++++++++++++++++++++++ 2 files changed, 29 insertions(+) create mode 100644 embassy/src/util/yield_now.rs diff --git a/embassy/src/util/mod.rs b/embassy/src/util/mod.rs index f832fa2f6..7744778bd 100644 --- a/embassy/src/util/mod.rs +++ b/embassy/src/util/mod.rs @@ -1,7 +1,11 @@ //! Misc utilities + mod forever; +mod yield_now; pub use forever::*; +pub use yield_now::*; + /// Unsafely unborrow an owned singleton out of a `&mut`. /// /// It is intended to be implemented for owned peripheral singletons, such as `USART3` or `AnyPin`. diff --git a/embassy/src/util/yield_now.rs b/embassy/src/util/yield_now.rs new file mode 100644 index 000000000..1ebecb916 --- /dev/null +++ b/embassy/src/util/yield_now.rs @@ -0,0 +1,25 @@ +use core::future::Future; +use core::pin::Pin; +use core::task::{Context, Poll}; + +/// Yield from the current task once, allowing other tasks to run. +pub fn yield_now() -> impl Future { + YieldNowFuture { yielded: false } +} + +struct YieldNowFuture { + yielded: bool, +} + +impl Future for YieldNowFuture { + type Output = (); + fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { + if self.yielded { + Poll::Ready(()) + } else { + self.yielded = true; + cx.waker().wake_by_ref(); + Poll::Pending + } + } +}