tokio
tokio copied to clipboard
docs: `tokio::sync::mpsc` can still be read when all senders are dropped
Current phrasing in tutorial:
When every Sender has gone out of scope or has otherwise been dropped, it is no longer possible to send more messages into the channel. At this point, the recv call on the Receiver will return None, which means that all senders are gone and the channel is closed.
The second statement is blatantly wrong because recv can still receive messages sent before senders drop.
use std::time::Duration;
use tokio::sync::mpsc;
use tokio::time::sleep;
#[tokio::main]
async fn main() {
let (tx, mut rx) = mpsc::channel(32);
let tx2 = tx.clone();
tokio::spawn(async move {
tx.send("sending from first handle").await.unwrap();
drop(tx);
println!("tx droppped");
});
tokio::spawn(async move {
tx2.send("sending from second handle").await.unwrap();
drop(tx2);
println!("tx2 droppped");
});
sleep(Duration::from_secs(2)).await;
while let Some(message) = rx.recv().await {
println!("GOT = {}", message);
}
}
In docs:
When all Sender handles have been dropped, it is no longer possible to send values into the channel. This is considered the termination event of the stream. As such, Receiver::poll returns Ok(Ready(None)).
This looks more correct but I have never tested with Receiver::poll.
I don't see a problem in the logic here. You are sending 2 strings over a channel, the channel has them in the queue and after consuming both strings the loop receives a None.
I think it is a fair point that the channel can return Some even though all senders are dropped.
I don't see a problem in the logic here. You are sending 2 strings over a channel, the channel has them in the queue and after consuming both strings the loop receives a None.
"after consuming both strings" is correct, but the current phrasing is "At this point" (of every Sender is dropped) which is not correct. That's why I introduced a delay in the output to show those are not the same point. Receivers can still receive messages already in the channel when every Sender is dropped.