gpt4 book ai didi

rust - 丢弃最后一个发件人但收信人仍处于事件状态时,是否可以在Tokio MPSC中保留项目?

转载 作者:行者123 更新时间:2023-12-03 11:30:31 25 4
gpt4 key购买 nike

我的Tokio MPSC队列有限,只有一个发送者和一个接收者。我在一个任务中放入了几项(在本例中为1到10,包括1和10),然后在另一项任务中将这些项拉出。如预期的那样,接收器处理所有10个值。
然后,我在处理之间添加了一些其他异步任务(在这种情况下,通过在接收循环中取消注释sleep调用),现在,最后一个发送者完成时, channel 的内容将被丢弃。

use tokio::sync::mpsc;
use tokio::time::sleep;
use std::time::Duration;

#[tokio::main]
async fn main() {
let (mut tx, mut rx) = mpsc::channel(3);

tokio::spawn(async move {
while let Some(val) = rx.recv().await {
println!("Recieved {}", val);
//sleep(Duration::from_secs(1)).await;
}

println!("Recieve finished");
});

for i in 1..=10i32 {
tx.send(i).await.unwrap();
println!("Sent {}", i);
}
}
Rust Playground
这是注释掉 sleep的输出(交错值的顺序有时会更改,但始终会打印“已接收10”):
Sent 1
Recieved 1
Recieved 2
Sent 2
Sent 3
Recieved 3
Recieved 4
Sent 4
Sent 5
Recieved 5
Recieved 6
Sent 6
Sent 7
Recieved 7
Recieved 8
Sent 8
Sent 9
Recieved 9
Recieved 10
Sent 10
这是未注释 sleep的输出:
Sent 1
Sent 2
Sent 3
Recieved 1
Sent 4
Recieved 2
Sent 5
Recieved 3
Sent 6
Recieved 4
Sent 7
Recieved 5
Sent 8
Recieved 6
Sent 9
Recieved 7
Sent 10
是否有任何方法可以确定即使删除了最后一个 Reciever后(假设没有删除 Sender), Reciever也处理了放入队列中的所有值? close函数似乎可以做到这一点,但是却是另一种方式(确保在删除 Reciever之前已处理了队列内容)。如果没有,是否存在可以提供此保证的备用异步友好MPSC实现?

最佳答案

如注释中所述,问题是您的程序在接收器线程完成之前退出。只需确保退出之前先等待即可:

use tokio::sync::mpsc;
use tokio::time::sleep;
use std::time::Duration;

#[tokio::main]
async fn main() {
let (mut tx, mut rx) = mpsc::channel(3);

let join_handle = tokio::spawn(async move {
while let Some(val) = rx.recv().await {
println!("Received {}", val);
//sleep(Duration::from_secs(1)).await;
}

println!("Receive finished");
});

for i in 1..=10i32 {
tx.send(i).await.unwrap();
println!("Sent {}", i);
}

std::mem::drop(tx); // Drop the sender so the receiver doesn't listen forever
join_handle.await.unwrap(); // Wait for the receiver to finish processing
}
Sent 1
Received 1
Received 2
Sent 2
Sent 3
Sent 4
Sent 5
Received 3
Received 4
Received 5
Sent 6
Sent 7
Sent 8
Received 6
Received 7
Received 8
Sent 9
Sent 10
Received 9
Received 10
Receive finished

关于rust - 丢弃最后一个发件人但收信人仍处于事件状态时,是否可以在Tokio MPSC中保留项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65501193/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com