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

implement try_join_next #6280

Merged
merged 9 commits into from
Jan 14, 2024
Merged
Show file tree
Hide file tree
Changes from 4 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
16 changes: 16 additions & 0 deletions tokio/src/task/join_set.rs
Original file line number Diff line number Diff line change
Expand Up @@ -306,6 +306,22 @@ impl<T: 'static> JoinSet<T> {
crate::future::poll_fn(|cx| self.poll_join_next_with_id(cx)).await
}

/// Tries to join one of the tasks in the set that has completed and return its output.
///
/// Returns `None` if the set is empty.
pub fn try_join_next(&mut self) -> Option<Result<T, JoinError>> {
let mut entry = self.inner.try_pop_notified()?;

let res = entry.with_value_and_context(|jh, ctx| Pin::new(jh).poll(ctx));

if let Poll::Ready(res) = res {
let _entry = entry.remove();
Some(res)
} else {
None
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This case happens if we successfully pop a JoinHandle from the list of notified tasks, but it turns out that the JoinHandle is not actually ready yet. In this case, we should not return None because there might be another JoinHandle in the list of notified task that is actually ready.

Instead, please wrap this function in a loop and go around the loop to try again in this case.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're right. Made the adjustments.

}

/// Aborts all tasks and waits for them to finish shutting down.
///
/// Calling this method is equivalent to calling [`abort_all`] and then calling [`join_next`] in
Expand Down
28 changes: 28 additions & 0 deletions tokio/src/util/idle_notified_set.rs
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,34 @@ impl<T> IdleNotifiedSet<T> {
Some(EntryInOneOfTheLists { entry, set: self })
}

/// Tries to pop an entry from the notified list to poll it. The entry is moved to
/// the idle list atomically.
pub(crate) fn try_pop_notified(&mut self) -> Option<EntryInOneOfTheLists<'_, T>> {
// We don't decrement the length because this call moves the entry to
// the idle list rather than removing it.
if self.length == 0 {
// Fast path.
return None;
}

let mut lock = self.lists.lock();

// Pop the entry, returning None if empty.
let entry = lock.notified.pop_back()?;

lock.idle.push_front(entry.clone());

// Safety: We are holding the lock.
entry.my_list.with_mut(|ptr| unsafe {
*ptr = List::Idle;
});

drop(lock);

// Safety: We just put the entry in the idle list, so it is in one of the lists.
Some(EntryInOneOfTheLists { entry, set: self })
}

/// Call a function on every element in this list.
pub(crate) fn for_each<F: FnMut(&mut T)>(&mut self, mut func: F) {
fn get_ptrs<T>(list: &mut LinkedList<T>, ptrs: &mut Vec<*mut T>) {
Expand Down
39 changes: 39 additions & 0 deletions tokio/tests/task_join_set.rs
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The test is nice. Especially the fact that you cover the case with coop budgeting. You don't have any tests that handle the case where it returns None even though there are tasks, because all the tasks are still running. Could you do that?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure!
I've updated the tests so they also test the case where there are no finished task.

Original file line number Diff line number Diff line change
Expand Up @@ -227,3 +227,42 @@ async fn join_set_coop() {
assert!(coop_count >= 1);
assert_eq!(count, TASK_NUM);
}

#[tokio::test(flavor = "current_thread")]
async fn try_join_next() {
// Large enough to trigger coop.
const TASK_NUM: u32 = 1000;

static SEM: tokio::sync::Semaphore = tokio::sync::Semaphore::const_new(0);

let mut set = JoinSet::new();

for _ in 0..TASK_NUM {
set.spawn(async {
SEM.add_permits(1);
});
}

// Wait for all tasks to complete.
//
// Since this is a `current_thread` runtime, there's no race condition
// between the last permit being added and the task completing.
let _ = SEM.acquire_many(TASK_NUM).await.unwrap();

let mut count = 0;
let mut coop_count = 0;
while count != TASK_NUM {
match set.try_join_next() {
Some(Ok(())) => {
count += 1;
}
Some(Err(err)) => panic!("failed: {}", err),
None => {
coop_count += 1;
tokio::task::yield_now().await;
}
}
}
assert!(coop_count >= 1);
assert_eq!(count, TASK_NUM);
}
Loading