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

when_any support #279

Open
Timmmm opened this issue Oct 28, 2024 · 2 comments
Open

when_any support #279

Timmmm opened this issue Oct 28, 2024 · 2 comments

Comments

@Timmmm
Copy link

Timmmm commented Oct 28, 2024

Would it be possible to have a when_any function, similar to when_all but it returns when the first awaitable is ready instead of waiting for all of them? Similar to Promise.race() in JS or select_all() in Rust.

@jbaldwin
Copy link
Owner

jbaldwin commented Nov 1, 2024

Hi @Timmmm

I had an issue for a long time considering adding it #153 , and I think its still a good idea. The trouble I ran into is that I'd probably need to introduce some type of cancellation token (or std::stop_token?) like behavior to every task. It would also be on the user to cancel the task if a stop was requested. So its possibly a large API change, or maybe it can be sorta shoe-horned in. But I haven't tried yet.

@Timmmm
Copy link
Author

Timmmm commented Nov 1, 2024

Wouldn't it just stop resuming the other tasks once one of them has finished? That would be fine for my use case at least. I'm not using the normal threading runtime though so I don't know if that's ok there...

You could return the tasks that didn't complete to the caller of when_any() so that it could resume them if it wants. Something like this (conceptually; obviously you don't want this actual API):

std::set<task<T>> tasks;

while (!tasks.empty()) {
  std::set<task<T>> remaining_tasks;
  task<T> completed_task;
  T return_value = co_await when_all(tasks, &remaining_tasks);
  tasks = remaining_tasks;
}

(Sorry if that's way off base; I'm a coroutine noob.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants