rust 实现协程池

时间:2021-07-19 16:57:38   收藏:0   阅读:0
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 来保证 所有 消息被释放

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!