我是Ruust异步编程的初学者.我正在编写一个程序来实现睡眠排序算法,该算法可以对非负数组进行排序.其实现原理是,对于数组中的每个元素,在输出之前等待一段时间,等待时间与元素的值成正比.这样,一段时间后,数组将按从小到大的顺序输出.
use std::time::Duration;
use text_io::read;
use tokio::sync::mpsc::channel;
#[tokio::main]
async fn main() {
let n: u32 = read!();
let (tx, mut rx) = channel::<u32>(n as usize);
let mut before: Vec<u32> = Vec::new();
for _ in 0..n {
let a = read!();
before.push(a);
}
for i in before.into_iter() {
let tx = tx.clone();
tokio::spawn(async move {
tokio::time::sleep(Duration::from_millis((50 * i) as u64)).await;
if let Err(_) = tx.send(i).await {
panic!();
}
});
}
while let Some(i) = rx.recv().await {
println!("{}", i);
}
}
该程序会打印正确的答案,但不会停止.我不知道为什么以及如何解决这个问题.