use crossbeam_channel::{Receiver, bounded}; use tokio::time::{Duration, delay_for}; #[tokio::main] async fn main() { let (s, r) = bounded(10); for i in 0..100 { s.send(i).unwrap(); let rx = r.clone(); tokio::task::spawn(async move { handle(i, rx).await; }); } delay_for(Duration::from_secs(10)).await; } async fn handle(i: i32, rx: Receiver<i32>) { let _d = defer::defer(|| { println!("{} been defer", i); if let Err(err) = rx.recv() { println!("err : {:?}", err); } }); delay_for(Duration::from_secs(1)).await; println!("{} been excute", i); }
使用 channel 做数量控制, defer 来保证 所有 消息被释放