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

Add FutureExt::also_poll #2840

Closed
wants to merge 1 commit into from

Conversation

coolreader18
Copy link
Contributor

@coolreader18 coolreader18 commented Mar 8, 2024

trait FutureExt {
    fn also_poll<Also>(self, also: Also) -> AlsoPoll<Self, Also> // Output = Self::Output
    where
        Self: Sized,
        Also: Future<Output = ()>,
    { // AlsoPoll pseudocode:
        let mut also = also.fuse();
        poll_fn(|cx| {
            let _ = also.poll(cx);
            self.poll(cx)
        })
    }
}

I've found this sort of function helpful when trying to avoid a Barbara Battles Buffered Streams type situation; specifically in my case, when you have a select-loop and one of the branches needs to await, but you don't want to starve something from another branch (pseudocode):

let mut fut = foo();
let mut stream = bar();
loop {
    select! {
        x = &mut fut => {
            do_thing_with(x);
            fut = foo();
        }
        y = stream.next() => {
            handle_stream_item(y).also_poll(&mut fut).await;
        }
    }
}

Without that .also_poll(&mut fut), fut would be starved of polls for the duration of handle_stream_item, potentially causing deadlocks or very long delays through the rest of the system if fut was queued to receive a semaphore permit (e.g. a mutex, a mpsc send() permit) because now it can't release it until handle_stream_item is done. That was my specific use case, at least, but I feel that this is a valuable primitive to have in general as folks start to look at stuff like Stream::poll_progress for combating BBBS (.also_poll(poll_fn(|cx| foo.poll_progress(cx))) is I feel a quintessential potential use case for this function).

Definitely open to naming suggestions, I feel like as it is it might not be super intuitive, but I do like how foo.also_poll(bar).await reads.

@coolreader18 coolreader18 changed the base branch from master to 0.3 March 8, 2024 21:10
@coolreader18
Copy link
Contributor Author

Not sure whether the base should be master or 0.3 - it's compatible with either but maybe 0.3 is just for bugfixes now?

@taiki-e
Copy link
Member

taiki-e commented Mar 9, 2024

Not sure whether the base should be master or 0.3

The base should bemaster. #2813

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

Successfully merging this pull request may close these issues.

None yet

2 participants