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

 

rust 实现协程池

上一篇:脱离OBDeploy工具,手工部署OceanBase方法


下一篇:Objective-C, 为什么不能在init或是dealloc方法中使用accessor方法