How to create a dedicated threadpool for CPU-intensive work in Tokio?

前端 未结 3 1672
感情败类
感情败类 2020-12-12 02:18

I have a Rust async server based on the Tokio runtime. It has to process a mix of latency-sensitive I/O-bound requests, and heavy CPU-bound requests.

I don\'t want t

3条回答
  •  萌比男神i
    2020-12-12 02:31

    Tokio's error message was misleading. The problem was due to Runtime object being dropped in an async context.

    The workaround is to use Handle, not Runtime directly, for spawning tasks on the other runtime.

    fn main() {
        let mut main_runtime = tokio::runtime::Runtime::new().unwrap();
        let cpu_pool = tokio::runtime::Builder::new().threaded_scheduler().build().unwrap();
    
        // this is the fix/workaround:
        let cpu_pool = cpu_pool.handle().clone(); 
    
        main_runtime.block_on(main_runtime.spawn(async move {
            cpu_pool.spawn(async {}).await
        }))
        .unwrap().unwrap();
    }
    

提交回复
热议问题