use select! oneshot "called after complete" error #3812
-
I want to use ** my code
** Error
|
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
The easiest is to use a channel that has support for using it after it has been closed such as an use tokio::sync::mpsc;
#[tokio::main]
async fn main() {
let (tx1, mut rx1) = mpsc::channel(1);
let (tx2, mut rx2) = mpsc::channel(1);
tokio::spawn(async move {
let _ = tx1.send("one").await;
});
tokio::spawn(async move {
let _ = tx2.send("two").await;
});
for _ in 0..2 {
tokio::select! {
Some(val) = rx1.recv() => {
println!("rx1 comopleted first with {:?}", val);
}
Some(val) = rx2.recv() => {
println!("rx2 comopleted first with {:?}", val);
}
}
}
} To do this with an oneshot channel, there are some options, but the easiest is to fuse it. use tokio::sync::oneshot;
use futures::future::FutureExt;
#[tokio::main]
async fn main() {
let (tx1, rx1) = oneshot::channel();
let (tx2, rx2) = oneshot::channel();
tokio::spawn(async move {
let _ = tx1.send("one");
});
tokio::spawn(async move {
let _ = tx2.send("two");
});
let mut rx1 = rx1.fuse();
let mut rx2 = rx2.fuse();
for _ in 0..2 {
tokio::select! {
val = &mut rx1 => {
println!("rx1 comopleted first with {:?}", val);
}
val = &mut rx2 => {
println!("rx2 comopleted first with {:?}", val);
}
}
}
} |
Beta Was this translation helpful? Give feedback.
-
I ran into this just recently. I was expecting tokio::sync::oneshot::Receiver to behave like a fused future. It seems really easy to implement to just return pending once the future is completed. Why does it panic instead, and would it be possible to change this behaviour to return pending? There is is_terminated as of tokio 1.44. |
Beta Was this translation helpful? Give feedback.
The easiest is to use a channel that has support for using it after it has been closed such as an
tokio::sync::mpsc
. Incidentally, this is also the channel that is closest to a Go channel.