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 .len() method to UnboundedSender #7077

Open
tqwewe opened this issue Jan 8, 2025 · 3 comments
Open

Add .len() method to UnboundedSender #7077

tqwewe opened this issue Jan 8, 2025 · 3 comments
Labels
A-tokio Area: The main tokio crate C-feature-request Category: A feature request. M-sync Module: tokio/sync

Comments

@tqwewe
Copy link

tqwewe commented Jan 8, 2025

Is your feature request related to a problem? Please describe.
The number of buffered messages can be derived from a bounded mpsc channel sender with len = tx.max_capacity() - tx.capacity(). However there's no methods available to get the number of buffered messages from an unbounded mpsc channel sender.

Describe the solution you'd like
A UnboundedSender::len() method which returns how many messages are buffered in the channel and pending to be received.

// Currently possible
let (boundex_tx, bounded_rx) = mpsc::channel(10);
let bounded_len = bounded_tx.max_capacity() - bounded.capacity();

// Proposed `len` method
let (unbounded_tx, unbounded_rx) = mpsc::unbounded_channel();
let unbounded_len = unbounded_tx.len();
@tqwewe tqwewe added A-tokio Area: The main tokio crate C-feature-request Category: A feature request. labels Jan 8, 2025
@conradludgate
Copy link
Contributor

For unbounded channels, the semaphore used counts up by 2 for each message sent, and subtracts 2 for each message received. So half the semaphore count could be used for such an implementation.

I do wonder what the usecase is for knowing the length from the sender. There's not a lot you can safely do with it (while avoiding race conditions)

@tqwewe
Copy link
Author

tqwewe commented Jan 8, 2025

Another related issue is #6314.

I do wonder what the usecase is for knowing the length from the sender.

In my case, I'm implementing a least-loaded kind of scheduler for a pool of actors. The pool stores the sender of each actor, and in order to forward a message to the actor with the least amount of load I could pick the actor in the pool with the smallest .len() value.

The alternative of course would be that the actor pool keeps a counter for each actor, but this brings some restrictions, particularly when the worker actors are generic actors defined by the user.

@Darksonn Darksonn added the M-sync Module: tokio/sync label Jan 8, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-tokio Area: The main tokio crate C-feature-request Category: A feature request. M-sync Module: tokio/sync
Projects
None yet
Development

No branches or pull requests

4 participants
@Darksonn @conradludgate @tqwewe and others