use std::sync::Arc;
use tokio::sync::mpsc;
async fn student(id : i32,tx : Arc<mpsc::Sender<String>>) {
println!("student {} is getting their hw.",id);
tx.send(format!("student {}'s hw !",id)).await.unwrap();
}
async fn teacher(mut rc : mpsc::Receiver<String>) -> Vec<String> {
let mut homeworks = Vec::new();
while let Some(hw) = rc.recv().await {
println!("{hw}");
homeworks.push(hw);
}
homeworks
}
#[tokio::main]
async fn main() {
let (tx,rc): (mpsc::Sender<String>, mpsc::Receiver<String>) = mpsc::channel(100);
let ch_arc: Arc<mpsc::Sender<String>> = Arc::new(tx);
for i in 0..10 {
tokio::task::spawn(student(i,ch_arc.clone()));
}
let hws = teacher(rc).await;
println!("{:?}",hws);
}
我目前正在学习Rust中的通道,现在我遇到了一些问题.问题是当我运行 teacher(rc).await
线时,
代码在这一点上卡住了,我不知道为什么会发生这种情况,但我在解决这个问题时观察到的一件事是,当我产生多个任务时,我会陷入循环,但当我只在student(i,ch_arc.clone());
行做一个spawn时,它工作得很好.
有人能帮我吗?