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

Fix starvation when using LIFO slot without consuming budget #5686

Merged
merged 4 commits into from
May 15, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
11 changes: 11 additions & 0 deletions tokio/src/runtime/coop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,17 @@ cfg_rt_multi_thread! {
pub(crate) fn set(budget: Budget) {
let _ = context::budget(|cell| cell.set(budget));
}

/// Consume one budget.
Darksonn marked this conversation as resolved.
Show resolved Hide resolved
pub(crate) fn consume_one() {
let _ = context::budget(|cell| {
let mut budget = cell.get();
if let Some(ref mut counter) = budget.0 {
*counter = counter.saturating_sub(1);
}
cell.set(budget);
});
}
}

cfg_rt! {
Expand Down
1 change: 1 addition & 0 deletions tokio/src/runtime/scheduler/multi_thread/worker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -479,6 +479,7 @@ impl Context {
None => return Ok(core),
};

coop::consume_one();
Darksonn marked this conversation as resolved.
Show resolved Hide resolved
if coop::has_budget_remaining() {
// Run the LIFO task, then loop
core.metrics.incr_poll_count();
Expand Down
29 changes: 28 additions & 1 deletion tokio/tests/rt_threaded.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,8 @@ fn single_thread() {
let _ = runtime::Builder::new_multi_thread()
.enable_all()
.worker_threads(1)
.build();
.build()
.unwrap();
}

#[test]
Expand Down Expand Up @@ -160,6 +161,32 @@ fn many_multishot_futures() {
}
}

#[test]
fn lifo_slot_budget() {
async fn my_fn() {
spawn_another();
}

fn spawn_another() {
tokio::spawn(my_fn());
}

let rt = runtime::Builder::new_multi_thread()
.enable_all()
.worker_threads(1)
.build()
.unwrap();

let (send, recv) = oneshot::channel();

rt.spawn(async move {
tokio::spawn(my_fn());
let _ = send.send(());
});

let _ = rt.block_on(recv);
}

#[test]
fn spawn_shutdown() {
let rt = rt();
Expand Down