Skip to content

Commit 3826627

Browse files
authored
Merge pull request #784 from wedsonaf/yield
rust: add async `yield_now`
2 parents d4b51d5 + 622c82a commit 3826627

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

rust/kernel/kasync.rs

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,5 +2,48 @@
22

33
//! Kernel async functionality.
44
5+
use core::{
6+
future::Future,
7+
pin::Pin,
8+
task::{Context, Poll},
9+
};
10+
511
#[cfg(CONFIG_NET)]
612
pub mod net;
13+
14+
/// Yields execution of the current task so that other tasks may execute.
15+
///
16+
/// The task continues to be in a "runnable" state though, so it will eventually run again.
17+
///
18+
/// # Examples
19+
///
20+
/// ```
21+
/// use kernel::kasync::yield_now;
22+
///
23+
/// async fn example() {
24+
/// pr_info!("Before yield\n");
25+
/// yield_now().await;
26+
/// pr_info!("After yield\n");
27+
/// }
28+
/// ```
29+
pub fn yield_now() -> impl Future<Output = ()> {
30+
struct Yield {
31+
first_poll: bool,
32+
}
33+
34+
impl Future for Yield {
35+
type Output = ();
36+
37+
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
38+
if !self.first_poll {
39+
Poll::Ready(())
40+
} else {
41+
self.first_poll = false;
42+
cx.waker().wake_by_ref();
43+
Poll::Pending
44+
}
45+
}
46+
}
47+
48+
Yield { first_poll: true }
49+
}

0 commit comments

Comments
 (0)