tokio-rs / tokio

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

Provide broadcast::Sender::new and watch::Sender::new functions #4958

Open JanBeh opened 2 years ago

JanBeh commented 2 years ago

Is your feature request related to a problem?

I'm planning to create an SDR framework where data is streamed between certain "processing blocks". These blocks can be dynamically connected with each other (and disconnected). I planned to use broadcast "channels" for that purpose. However, when I create a producer, I might not have a consumer (yet), so I would only need a broadcast::Sender. There is currently no way to create a Sender without also creating a Receiver.

A similar situation applies to tokio::sync::watch, where it's also not possible to create a Sender without a Receiver.

Describe the solution you'd like

I propose to add the following associated functions

which act like

with the difference that the receiver isn't needlessly created and then dropped.

Describe alternatives you've considered

Using .0 on the (Sender, Receiver) pair is a good workaround, but might have unnecessary runtime overhead and is also less readable/verbose. Compare:

let x = broadcast::Sender::<T>::new(16);

vs

let x = broadcast::channel::<T>(16).0;

Additional context

Also note #4957.

JanBeh commented 2 years ago

Apparently Senders without Receivers show some (maybe) surprising behavior:

use tokio::sync::watch;

#[allow(unused_variables)]
fn main() {
    let (sender, receiver) = watch::channel("initial");
    //drop(receiver); // try to uncomment
    sender.send("updated").ok();
    let receiver2 = sender.subscribe();
    let s = *receiver2.borrow();
    assert_eq!(s, "updated"); // fails if `receiver` is dropped before `send`
}

See also this post on URLO.

The other send methods (send_if_modified, send_modify, or send_replace) don't exhibit this behavior, so the proposed feature is still useful.

marcospb19 commented 1 year ago

I was also surprised by this, you can call broadcast::channel::<T>(CAPACITY).0 and send messages with the sender, they'll return an error, but you can just ignore them.

That's ok for broadcasts where you lose all messages previous to subscribing, implementing something else would be hard considering how it currently works.

Regarding watch, I think that's odd, it should be possible to set a value before there are listeners and get it later with watch::Receiver::borrow.

Darksonn commented 1 year ago

You can actually send a value without any receivers on a watch channel if you use send_modify.

The send method cannot be changed to allow this for backwards compatibility reasons.

Darksonn commented 1 year ago

Reopening since this also applies to the watch channel.