tokio-rs / tokio

A runtime for writing reliable asynchronous applications with Rust. Provides I/O, networking, scheduling, timers, ...
https://tokio.rs
MIT License
25.73k stars 2.35k forks source link

Allow Notify to wake up exactly one waiter #6587

Closed kaimast closed 1 month ago

kaimast commented 1 month ago

Motivation

I maintain tokio-condvar, which is a crate that provides an async version of std::sync::Condvar building on top of tokio's Notify.

Right now, there is no efficient way to implement Condvar::notify_one, as Notify only provides a way to wake up all wakers. My current implementation simply uses Notify::notify_waiters in this case, which wakes up all waiters.

Solution

This pull requests adds Notify::notify_one_waiter, which behaves like Notify::notify_waiters, but wakes up at most one waiter.

Darksonn commented 1 month ago

I'm reluctant to add even more methods to Notify. If notify_waiters is a correct implementation, then that means that you allow spurious wakeups. In that case, the existing notify_one seems reasonably similar to what you need.

kaimast commented 1 month ago

Thank you for the feedback, Alice.

I'm reluctant to add even more methods to Notify.

That is a fair point. Feel free to close the pull request then.

If notify_waiters is a correct implementation, then that means that you allow spurious wakeups. In that case, the existing notify_one seems reasonably similar to what you need.

I think you're right. There might be a few more spurious wakeups when using notify_one, but it probably does not matter in the grand scheme of things.