Skip to content

feat: wait_until method for the wait_queue #1057

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

Open
wants to merge 5 commits into
base: master
Choose a base branch
from

Conversation

Ddystopia
Copy link
Contributor

For some reason github cannot understand that this is the same branch, so I forced to make the second PR after #1052

Diatomic Waker has a method like this and it is very handy. I've been implementing async wrapper over heapless::mpmc::MpMcQueue and wait_queue is great, but a method like this is really benefitial. You can safely create async versions of enqueue and dequeue, and don't need unsafe to interact with the wait_queue.

Note that this PR has only 1 additional unsafe block.

To give a perspective, this method is used like that :

impl<T, const N: usize> MpMcChannel<T, N> {
    pub const fn new() -> Self {
        Self {
            tx_wait_queue: WaitQueue::new(),
            rx_wait_queue: WaitQueue::new(),
            queue: MpMcQueue::new(),
        }
    }

    pub fn try_send(&self, value: T) -> Result<(), T> {
        while let Some(waker) = self.rx_wait_queue.pop() {
            waker.wake();
        }

        self.queue.enqueue(value)
    }

    pub fn try_recv(&self) -> Option<T> {
        while let Some(waker) = self.rx_wait_queue.pop() {
            waker.wake();
        }

        self.queue.dequeue()
    }

    pub async fn send(&self, value: T) {
        let mut value = Some(value);
        self.tx_wait_queue
            .wait_until(|| {
                self.try_send(value.take().expect("Future is polled after completion"))
                    .map_err(|old_val| value = Some(old_val))
                    .ok()
            })
            .await
    }

    pub async fn recv(&self) -> T {
        self.rx_wait_queue.wait_until(|| self.try_recv()).await
    }
}

@Ddystopia
Copy link
Contributor Author

@AfoHT #1052 moved there

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.

1 participant