rust 实现协程池

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 来保证 所有 消息被释放

 

posted @ 2021-07-19 13:42  ma_fighting  阅读(551)  评论(0编辑  收藏  举报
历史天气查