当我跑步时
use tokio::sync::mpsc;
#[tokio::main(flavor = "multi_thread", worker_threads = 1)]
async fn main() {
let (tx, mut rx) = mpsc::channel(1);
tokio::spawn(async move {
while let Some(i) = rx.recv().await {
println!("got = {}", i);
}
});
for i in 0..5 {
// busy calculation
std::thread::sleep(std::time::Duration::from_millis(10));
match tx.try_send(i) {
Ok(_) => {
println!("sent = {}", i);
},
Err(err) => {
println!("{}", err);
}
};
};
}
我得到了
sent = 0
got = 0
sent = 1
got = 1
sent = 2
got = 2
sent = 3
got = 3
sent = 4
据我了解,唯一的工作者正在处理 for 循环,因为它从不产生结果。唯一的工作者应该没有机会处理接收。因此,通道在第一次发送后应该是满的。结果我错了。我遗漏了什么?