Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

macros: make select! budget-aware #7164

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions tokio/src/macros/select.rs
Original file line number Diff line number Diff line change
Expand Up @@ -660,6 +660,14 @@ doc! {macro_rules! select {
let mut futures = &mut futures;

$crate::macros::support::poll_fn(|cx| {
// Return `Pending` when the task budget is depleted since budget-aware futures
// are going to yield anyway and other futures will not cooperate.
if !$crate::macros::support::has_budget_remaining() {
cx.waker().wake_by_ref();

return ::std::task::Poll::Pending;
}

// Track if any branch returns pending. If no branch completes
// **or** returns pending, this implies that all branches are
// disabled.
Expand Down
8 changes: 8 additions & 0 deletions tokio/src/macros/support.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,14 @@ cfg_macros! {
pub fn thread_rng_n(n: u32) -> u32 {
crate::runtime::context::thread_rng_n(n)
}

#[doc(hidden)]
pub fn has_budget_remaining() -> bool {
#[cfg(feature = "rt")]
{ crate::task::coop::has_budget_remaining() }
#[cfg(not(feature = "rt"))]
{ true }
}
}

pub use std::future::{Future, IntoFuture};
Expand Down
24 changes: 24 additions & 0 deletions tokio/tests/macros_select.rs
Original file line number Diff line number Diff line change
Expand Up @@ -716,3 +716,27 @@ async fn temporary_lifetime_extension() {
() = &mut std::future::ready(()) => {},
}
}

#[tokio::test]
async fn select_is_budget_aware() {
const BUDGET: usize = 128;

let task = || {
Box::pin(async move {
tokio::select! {
biased;

() = tokio::task::coop::consume_budget() => {},
() = std::future::ready(()) => {}
}
})
};

for _ in 0..BUDGET {
let poll = futures::poll!(&mut task());
assert!(poll.is_ready());
}

let poll = futures::poll!(&mut task());
assert!(poll.is_pending());
}
Loading